Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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() ?

like image 469
flq Avatar asked Nov 13 '18 20:11

flq


People also ask

How do I get the return type of method in TypeScript?

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.

How do I return a class in TypeScript?

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; };

How do you define a method of a class in TypeScript?

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 .

How do you define return type?

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.


1 Answers

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

type FooReturnType = ReturnType<MyClass['foo']>; 
like image 137
artem Avatar answered Sep 26 '22 08:09

artem