How do I get the return type of a class method in TypeScript

11k views Asked by At

In newer TypeScript versions (I think 2.8 onwards?), I can easily obtain the return type of a function:

function f() { return "hi"; }
type MyType = ReturnType<typeof f>; //MyType is string

But I can't figure out to get the same info from a class method…

class MyClass {
  foo() { return "hi"; }
}

How do I get the return type of (new MyClass()).foo() ?

1

There are 1 answers

1
artem On BEST ANSWER

To get property or method type, you can use indexed access type operator:

type FooReturnType = ReturnType<MyClass['foo']>;