EN
TypeScript - get function return type
5 points
In this short article we would like to show how to get type of object returned by function in TypeScript.
Quick solution:
xxxxxxxxxx
1
const MyFunction = (): string => { return ''; }
2
type MyType = ReturnType<typeof MyFunction>; // string
Practical example:
xxxxxxxxxx
1
type Action1 = () => void;
2
type Action2 = () => string;
3
4
const Function1 = (): void => {
5
console.log('void return');
6
};
7
const Function2 = (text: string): string => {
8
return `Text: ${text}`;
9
};
10
11
type Action1Result = ReturnType<Action1>; // void
12
type Action2Result = ReturnType<Action2>; // string
13
14
type Function1Result = ReturnType<typeof Function1>; // void
15
type Function2Result = ReturnType<typeof Function2>; // string
16
17
type Function1Result = ReturnType<() => void>; // void
18
type Function2Result = ReturnType<() => string>; // string