简体   繁体   中英

Infer class generic property method return type

I'm having trouble inferring the return type of class generic property.

I have this simple setup that works:

class A<T extends B> {
  constructor(public b: T) {}

  getB() {
    return this.b
  }

  bMethodResult() {
    return this.b.methodOne()
  }
}

class B {
  methodOne() {
    return { status: 'ok' }
  }
}

const aOne = new A(new B())

aOne.getB() // :B

aOne.bMethodResult() // {status:string}

As you can see TS correctly infers the return type of aOne.bMethodResult() . However, if I try to pass in a child of the B class with a different method signature, TS is not updating the return type to be the B child class method.

class BChild extends B {
  methodOne() {
    return { status: 'ok', data: true }
  }
}

const aTwo = new A(new BChild())

aTwo.getB() // : BChild // ok

aTwo.bMethodResult() // : {status:string }
// I want it to be {status:string, data:boolean}

Is there a way I could get the return type of the child class?

TS Playground

You could do this by adding a return type to bMethodResult :

class A<T extends B> {
  // ...

  bMethodResult(): ReturnType<T['methodOne']> {
    return this.b.methodOne() as ReturnType<T['methodOne']>
  }
}

// ...

aTwo.bMethodResult() // : {status:string, data: boolean}

However, this requires a type assertion because TypeScript infers this.b.methodOne() to be {status: string} instead of ReturnType<T['methodOne']> .

Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM