Typescript: Infer "this" from extended classes

Created on 30 Jul 2017  路  3Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.4.0

Code

class B {
    static make() {
        return new this;
    }
}

class A extends B {
    id = 1;
}

console.log(typeof A.make().id);

Expected behavior:
A.make().id can be inferred to be the id (1)

Actual behavior:
A.make() is typehinted to return "B" where it returns "A" at runtime.

this inference

Duplicate

Most helpful comment

Give this a try

class B {
    static make<T extends typeof B>(this: T): T['prototype'] {
        return new this();
    }
}

class A extends B {
    id = 1;
}

console.log(A.make().id);

It is a bit ugly, and there may be a more concise way to write it, but you only need to specify it once.

Note that T is inferred as A because it is the type of the this argument.

All 3 comments

Give this a try

class B {
    static make<T extends typeof B>(this: T): T['prototype'] {
        return new this();
    }
}

class A extends B {
    id = 1;
}

console.log(A.make().id);

It is a bit ugly, and there may be a more concise way to write it, but you only need to specify it once.

Note that T is inferred as A because it is the type of the this argument.

I've never seen that syntax before. It works, thanks a lot!

Dupe of #5863.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

blendsdk picture blendsdk  路  3Comments

weswigham picture weswigham  路  3Comments