How to typescript `this` when it is dynamic?












1















I'm converting a series of JavaScript projects to typescript, and a common paradigm that I've used has been the following:



abstract class A {
static create (…args) {
return new this(…args)
}
/* a bunch of things */
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
/* a bunch of things */
}

class C extends A {
/* a bunch of things */
}


Which offers the compelling syntactic sugar of require('module').B.create().



I cannot figure out how to make this valid typescript.



Additional complexity, is that consumers of the package may also extend class A too, so I am not aware of all the extensions at the time of authorship.





With:



abstract class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get the error:




[ts] Cannot create an instance of an abstract class. [2511]






With the following, that omits the abstract for debugging:



class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get an error about the variable arguments:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



type StaticThis<T> = { new(): T };

abstract class A {
static create<T extends typeof A>(this: StaticThis<T>, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I solve the abstract error, but keep the arguments error:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



interface Factory<T> {
new(...args: any): T
}

abstract class A {
static create<T extends A>(this: Factory<T>, ...args: any): T {
return new this(...args)
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
foo() {

}
}

class C extends A {
bar() {

}
}


It works as expected, however Visual Studio Code autocompletes B.create to B.create(this), which may be a seperate bug.










share|improve this question




















  • 1





    Is this your issue?

    – jcalz
    Nov 20 '18 at 1:13











  • @jcalz thank you, it seems so, want to post the typescript compatible code snippet in an answer so I can mark it as such.

    – balupton
    Nov 20 '18 at 1:15
















1















I'm converting a series of JavaScript projects to typescript, and a common paradigm that I've used has been the following:



abstract class A {
static create (…args) {
return new this(…args)
}
/* a bunch of things */
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
/* a bunch of things */
}

class C extends A {
/* a bunch of things */
}


Which offers the compelling syntactic sugar of require('module').B.create().



I cannot figure out how to make this valid typescript.



Additional complexity, is that consumers of the package may also extend class A too, so I am not aware of all the extensions at the time of authorship.





With:



abstract class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get the error:




[ts] Cannot create an instance of an abstract class. [2511]






With the following, that omits the abstract for debugging:



class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get an error about the variable arguments:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



type StaticThis<T> = { new(): T };

abstract class A {
static create<T extends typeof A>(this: StaticThis<T>, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I solve the abstract error, but keep the arguments error:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



interface Factory<T> {
new(...args: any): T
}

abstract class A {
static create<T extends A>(this: Factory<T>, ...args: any): T {
return new this(...args)
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
foo() {

}
}

class C extends A {
bar() {

}
}


It works as expected, however Visual Studio Code autocompletes B.create to B.create(this), which may be a seperate bug.










share|improve this question




















  • 1





    Is this your issue?

    – jcalz
    Nov 20 '18 at 1:13











  • @jcalz thank you, it seems so, want to post the typescript compatible code snippet in an answer so I can mark it as such.

    – balupton
    Nov 20 '18 at 1:15














1












1








1








I'm converting a series of JavaScript projects to typescript, and a common paradigm that I've used has been the following:



abstract class A {
static create (…args) {
return new this(…args)
}
/* a bunch of things */
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
/* a bunch of things */
}

class C extends A {
/* a bunch of things */
}


Which offers the compelling syntactic sugar of require('module').B.create().



I cannot figure out how to make this valid typescript.



Additional complexity, is that consumers of the package may also extend class A too, so I am not aware of all the extensions at the time of authorship.





With:



abstract class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get the error:




[ts] Cannot create an instance of an abstract class. [2511]






With the following, that omits the abstract for debugging:



class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get an error about the variable arguments:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



type StaticThis<T> = { new(): T };

abstract class A {
static create<T extends typeof A>(this: StaticThis<T>, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I solve the abstract error, but keep the arguments error:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



interface Factory<T> {
new(...args: any): T
}

abstract class A {
static create<T extends A>(this: Factory<T>, ...args: any): T {
return new this(...args)
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
foo() {

}
}

class C extends A {
bar() {

}
}


It works as expected, however Visual Studio Code autocompletes B.create to B.create(this), which may be a seperate bug.










share|improve this question
















I'm converting a series of JavaScript projects to typescript, and a common paradigm that I've used has been the following:



abstract class A {
static create (…args) {
return new this(…args)
}
/* a bunch of things */
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
/* a bunch of things */
}

class C extends A {
/* a bunch of things */
}


Which offers the compelling syntactic sugar of require('module').B.create().



I cannot figure out how to make this valid typescript.



Additional complexity, is that consumers of the package may also extend class A too, so I am not aware of all the extensions at the time of authorship.





With:



abstract class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get the error:




[ts] Cannot create an instance of an abstract class. [2511]






With the following, that omits the abstract for debugging:



class A {
static create<T extends typeof A>(this: T, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I get an error about the variable arguments:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



type StaticThis<T> = { new(): T };

abstract class A {
static create<T extends typeof A>(this: StaticThis<T>, ...args: any): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }


I solve the abstract error, but keep the arguments error:




[ts] Expected 0 arguments, but got 1 or more. [2556]






With:



interface Factory<T> {
new(...args: any): T
}

abstract class A {
static create<T extends A>(this: Factory<T>, ...args: any): T {
return new this(...args)
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
foo() {

}
}

class C extends A {
bar() {

}
}


It works as expected, however Visual Studio Code autocompletes B.create to B.create(this), which may be a seperate bug.







typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 1:50







balupton

















asked Nov 20 '18 at 1:07









baluptonbalupton

30.9k23104154




30.9k23104154








  • 1





    Is this your issue?

    – jcalz
    Nov 20 '18 at 1:13











  • @jcalz thank you, it seems so, want to post the typescript compatible code snippet in an answer so I can mark it as such.

    – balupton
    Nov 20 '18 at 1:15














  • 1





    Is this your issue?

    – jcalz
    Nov 20 '18 at 1:13











  • @jcalz thank you, it seems so, want to post the typescript compatible code snippet in an answer so I can mark it as such.

    – balupton
    Nov 20 '18 at 1:15








1




1





Is this your issue?

– jcalz
Nov 20 '18 at 1:13





Is this your issue?

– jcalz
Nov 20 '18 at 1:13













@jcalz thank you, it seems so, want to post the typescript compatible code snippet in an answer so I can mark it as such.

– balupton
Nov 20 '18 at 1:15





@jcalz thank you, it seems so, want to post the typescript compatible code snippet in an answer so I can mark it as such.

– balupton
Nov 20 '18 at 1:15












2 Answers
2






active

oldest

votes


















2














I think a minor modification to the code alluded to in the relevant issue will also give you the proper constructor argument checking for each subclass, at least since TypeScript 3.0 introduced generic rest parameters:



type StaticThis<Args extends any, T> = { new(...args: Args): T };

abstract class A {
public static create<Args extends any, T extends A>(
this: StaticThis<Args, T>,
...args: Args
): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }

const b = B.create(1, "b"); // okay
const c = C.create(); // okay
const badB = B.create(2, 3); // error, type '3' not assignable to type 'string';
const badC = C.create(4); // error, expected 0 arguments
const badA = A.create(); // error, can't use abstract class here


I'm kind of not sure about why you'd rather jump through these hoops instead of just using new on the subclasses, but you probably have your reasons.



Hope that helps. Good luck!






share|improve this answer
























  • Perfect, thank you so much!

    – balupton
    Nov 20 '18 at 3:50



















0














File 1 =>



 export namespace Shapes {
export namespace Polygons {

export class A {
static create <T extends A>(): T {
return <T>new this();
}

sayHi(){
console.log('Hi')
}
}

export class B extends A{
sayHiFromB() {
console.log('Hi From B');
}
}
}
}


File 2 =>



import * as myImport from './testing';


const myInstanceA = myImport.Shapes.Polygons.A.create();
myInstanceA.sayHi();


const myInstanceB = myImport.Shapes.Polygons.B.create<myImport.Shapes.Polygons.B>();
myInstanceB.sayHi();
myInstanceB.sayHiFromB();


Result =>
Result =>






share|improve this answer
























  • This drops the abstract and also removes the support for passing arguments to the extended classes.

    – balupton
    Nov 20 '18 at 1:31













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384818%2fhow-to-typescript-this-when-it-is-dynamic%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














I think a minor modification to the code alluded to in the relevant issue will also give you the proper constructor argument checking for each subclass, at least since TypeScript 3.0 introduced generic rest parameters:



type StaticThis<Args extends any, T> = { new(...args: Args): T };

abstract class A {
public static create<Args extends any, T extends A>(
this: StaticThis<Args, T>,
...args: Args
): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }

const b = B.create(1, "b"); // okay
const c = C.create(); // okay
const badB = B.create(2, 3); // error, type '3' not assignable to type 'string';
const badC = C.create(4); // error, expected 0 arguments
const badA = A.create(); // error, can't use abstract class here


I'm kind of not sure about why you'd rather jump through these hoops instead of just using new on the subclasses, but you probably have your reasons.



Hope that helps. Good luck!






share|improve this answer
























  • Perfect, thank you so much!

    – balupton
    Nov 20 '18 at 3:50
















2














I think a minor modification to the code alluded to in the relevant issue will also give you the proper constructor argument checking for each subclass, at least since TypeScript 3.0 introduced generic rest parameters:



type StaticThis<Args extends any, T> = { new(...args: Args): T };

abstract class A {
public static create<Args extends any, T extends A>(
this: StaticThis<Args, T>,
...args: Args
): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }

const b = B.create(1, "b"); // okay
const c = C.create(); // okay
const badB = B.create(2, 3); // error, type '3' not assignable to type 'string';
const badC = C.create(4); // error, expected 0 arguments
const badA = A.create(); // error, can't use abstract class here


I'm kind of not sure about why you'd rather jump through these hoops instead of just using new on the subclasses, but you probably have your reasons.



Hope that helps. Good luck!






share|improve this answer
























  • Perfect, thank you so much!

    – balupton
    Nov 20 '18 at 3:50














2












2








2







I think a minor modification to the code alluded to in the relevant issue will also give you the proper constructor argument checking for each subclass, at least since TypeScript 3.0 introduced generic rest parameters:



type StaticThis<Args extends any, T> = { new(...args: Args): T };

abstract class A {
public static create<Args extends any, T extends A>(
this: StaticThis<Args, T>,
...args: Args
): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }

const b = B.create(1, "b"); // okay
const c = C.create(); // okay
const badB = B.create(2, 3); // error, type '3' not assignable to type 'string';
const badC = C.create(4); // error, expected 0 arguments
const badA = A.create(); // error, can't use abstract class here


I'm kind of not sure about why you'd rather jump through these hoops instead of just using new on the subclasses, but you probably have your reasons.



Hope that helps. Good luck!






share|improve this answer













I think a minor modification to the code alluded to in the relevant issue will also give you the proper constructor argument checking for each subclass, at least since TypeScript 3.0 introduced generic rest parameters:



type StaticThis<Args extends any, T> = { new(...args: Args): T };

abstract class A {
public static create<Args extends any, T extends A>(
this: StaticThis<Args, T>,
...args: Args
): T {
const Klass = this
const instance = new Klass(...args)
return instance
}
}

class B extends A {
a: number
b: string
constructor(a: number, b: string) {
super()
this.a = a
this.b = b
}
}

class C extends A { }

const b = B.create(1, "b"); // okay
const c = C.create(); // okay
const badB = B.create(2, 3); // error, type '3' not assignable to type 'string';
const badC = C.create(4); // error, expected 0 arguments
const badA = A.create(); // error, can't use abstract class here


I'm kind of not sure about why you'd rather jump through these hoops instead of just using new on the subclasses, but you probably have your reasons.



Hope that helps. Good luck!







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 '18 at 2:01









jcalzjcalz

24.7k22244




24.7k22244













  • Perfect, thank you so much!

    – balupton
    Nov 20 '18 at 3:50



















  • Perfect, thank you so much!

    – balupton
    Nov 20 '18 at 3:50

















Perfect, thank you so much!

– balupton
Nov 20 '18 at 3:50





Perfect, thank you so much!

– balupton
Nov 20 '18 at 3:50













0














File 1 =>



 export namespace Shapes {
export namespace Polygons {

export class A {
static create <T extends A>(): T {
return <T>new this();
}

sayHi(){
console.log('Hi')
}
}

export class B extends A{
sayHiFromB() {
console.log('Hi From B');
}
}
}
}


File 2 =>



import * as myImport from './testing';


const myInstanceA = myImport.Shapes.Polygons.A.create();
myInstanceA.sayHi();


const myInstanceB = myImport.Shapes.Polygons.B.create<myImport.Shapes.Polygons.B>();
myInstanceB.sayHi();
myInstanceB.sayHiFromB();


Result =>
Result =>






share|improve this answer
























  • This drops the abstract and also removes the support for passing arguments to the extended classes.

    – balupton
    Nov 20 '18 at 1:31


















0














File 1 =>



 export namespace Shapes {
export namespace Polygons {

export class A {
static create <T extends A>(): T {
return <T>new this();
}

sayHi(){
console.log('Hi')
}
}

export class B extends A{
sayHiFromB() {
console.log('Hi From B');
}
}
}
}


File 2 =>



import * as myImport from './testing';


const myInstanceA = myImport.Shapes.Polygons.A.create();
myInstanceA.sayHi();


const myInstanceB = myImport.Shapes.Polygons.B.create<myImport.Shapes.Polygons.B>();
myInstanceB.sayHi();
myInstanceB.sayHiFromB();


Result =>
Result =>






share|improve this answer
























  • This drops the abstract and also removes the support for passing arguments to the extended classes.

    – balupton
    Nov 20 '18 at 1:31
















0












0








0







File 1 =>



 export namespace Shapes {
export namespace Polygons {

export class A {
static create <T extends A>(): T {
return <T>new this();
}

sayHi(){
console.log('Hi')
}
}

export class B extends A{
sayHiFromB() {
console.log('Hi From B');
}
}
}
}


File 2 =>



import * as myImport from './testing';


const myInstanceA = myImport.Shapes.Polygons.A.create();
myInstanceA.sayHi();


const myInstanceB = myImport.Shapes.Polygons.B.create<myImport.Shapes.Polygons.B>();
myInstanceB.sayHi();
myInstanceB.sayHiFromB();


Result =>
Result =>






share|improve this answer













File 1 =>



 export namespace Shapes {
export namespace Polygons {

export class A {
static create <T extends A>(): T {
return <T>new this();
}

sayHi(){
console.log('Hi')
}
}

export class B extends A{
sayHiFromB() {
console.log('Hi From B');
}
}
}
}


File 2 =>



import * as myImport from './testing';


const myInstanceA = myImport.Shapes.Polygons.A.create();
myInstanceA.sayHi();


const myInstanceB = myImport.Shapes.Polygons.B.create<myImport.Shapes.Polygons.B>();
myInstanceB.sayHi();
myInstanceB.sayHiFromB();


Result =>
Result =>







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 '18 at 1:30









Gabriel LopezGabriel Lopez

2827




2827













  • This drops the abstract and also removes the support for passing arguments to the extended classes.

    – balupton
    Nov 20 '18 at 1:31





















  • This drops the abstract and also removes the support for passing arguments to the extended classes.

    – balupton
    Nov 20 '18 at 1:31



















This drops the abstract and also removes the support for passing arguments to the extended classes.

– balupton
Nov 20 '18 at 1:31







This drops the abstract and also removes the support for passing arguments to the extended classes.

– balupton
Nov 20 '18 at 1:31




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384818%2fhow-to-typescript-this-when-it-is-dynamic%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to send String Array data to Server using php in android

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

Is anime1.com a legal site for watching anime?