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:
const MyFunction = (): string => { return ''; }
type MyType = ReturnType<typeof MyFunction>; // string
Practical example:
type Action1 = () => void;
type Action2 = () => string;
const Function1 = (): void => {
console.log('void return');
};
const Function2 = (text: string): string => {
return `Text: ${text}`;
};
type Action1Result = ReturnType<Action1>; // void
type Action2Result = ReturnType<Action2>; // string
type Function1Result = ReturnType<typeof Function1>; // void
type Function2Result = ReturnType<typeof Function2>; // string
type Function1Result = ReturnType<() => void>; // void
type Function2Result = ReturnType<() => string>; // string