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

uber5001 picture uber5001  ·  3Comments

siddjain picture siddjain  ·  3Comments

blendsdk picture blendsdk  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

fwanicka picture fwanicka  ·  3Comments