This compiles just fine:
class Foo<F> {
bar: Array<F> = [];
static create<F, T extends Foo<F>>(this: new () => T): T {
return new this();
}
}
class Foo2 extends Foo<string> {}
const foo = Foo2.create();
But if I convert Array<F> to Array<(a: F) => void>, the same code fails:
class Foo<F> {
bar: Array<(a: F) => void> = [];
static create<F, T extends Foo<F>>(this: new () => T): T {
return new this();
}
}
class Foo2 extends Foo<string> {}
const foo = Foo2.create();
^^^
The 'this' context of type 'typeof Foo2' is not assignable to method's 'this' of type 'new () => Foo<unknown>'.
Types of construct signatures are incompatible.
Type 'new () => Foo2' is not assignable to type 'new () => Foo<unknown>'.
Type 'Foo2' is not assignable to type 'Foo<unknown>'.
Type 'unknown' is not assignable to type 'string'. ts(2684)
It works if I type it manually:
const foo = Foo2.create<string, Foo2>();
So for some reason TypeScript can't infer the string type if it's used in a function argument. Why is this?
thisis a reserved word, this could make issueThisType.