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()
?
Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.
You need to export the class as well so that the consumer of the method can access the type. Typically a factory will return an instance rather than a class or constructor. export class Foo {}; export let factory = () => { return Foo; };
In TypeScript, the constructor method is always defined with the name "constructor". In the above example, the Employee class includes a constructor with the parameters empcode and name . In the constructor, members of the class can be accessed using this keyword e.g. this. empCode or this.name .
In computer programming, the return type (or result type) defines and constrains the data type of the value returned from a subroutine or method. In many programming languages (especially statically-typed programming languages such as C, C++, Java) the return type must be explicitly specified when declaring a function.
To get property or method type, you can use indexed access type operator:
type FooReturnType = ReturnType<MyClass['foo']>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With