TSR
TSR

Reputation: 20406

Typescript return typeof of "this"

I use a library called Foo that you use by extending any other class. All methods of Foo return this.

So Typescript should understand that fromJson is the same type of the class BarFoo but it doesn't

// library
class Foo {
    fromJson(obj:any) {
        if(obj == null) return obj;
        Object.assign(this, obj)
        // something else here
        return this;
    }
}
// usage
class BarFoo extends Foo{
    id:string
    foo(){

    }
}
const barFoo = new BarFoo().fromJson({id: 'foo'})
barFoo.foo(); // should have autocompleted foo()
barFoo.somethingNotExisting(); // should have errored out

Upvotes: 0

Views: 105

Answers (2)

tmhao2005
tmhao2005

Reputation: 17474

Since you also have a case of return null which means the correct type should be this | null:

class Foo {
    fromJson(obj: any): this | null {
      //
    }
}

So to use with strict mode enabled in tsconfig.json, you might have to check nullable before using:

const barFoo = new BarFoo().fromJson({id: 'foo'})
barFoo?.foo()

Upvotes: 2

Daniele_s
Daniele_s

Reputation: 116

The problem here is the first return: if(obj == null) return obj;. Typescript is inferring that the return type of fromJson is any.

You can solve it returning null directly: if(obj == null) return null; or annotating the method with the return type fromJson(obj: any): this {.

Be aware that with both solutions you end up having a possible null returned from the method. So the real return type whould be this | null.

Upvotes: 3

Related Questions