Is there a way in typescript to easily get the return type of the function you're currently in?
Eg
const fn = (): (some complex type that I don't want to repeat or name)[] => {
const result: ReturnTypeOfThisFunction = [];
// generate result
return result;
};
I want to have the function itself have an explicit type, not derive it from the return value, but also not repeat the type within the function body, or declare a type
just for this one-off function.
If the function was a named top level function I could just do ReturnType<typeof functionName>
but if it's an anonymous function, or one within a class, object, etc, then this gets increasingly complicated
Is there a way in typescript to easily get the return type of the function you're currently in?
Eg
const fn = (): (some complex type that I don't want to repeat or name)[] => {
const result: ReturnTypeOfThisFunction = [];
// generate result
return result;
};
I want to have the function itself have an explicit type, not derive it from the return value, but also not repeat the type within the function body, or declare a type
just for this one-off function.
If the function was a named top level function I could just do ReturnType<typeof functionName>
but if it's an anonymous function, or one within a class, object, etc, then this gets increasingly complicated
- Please edit this code to be a minimal reproducible example without pseudocode and where we can play around with it in our IDEs. – jcalz Commented Nov 19, 2024 at 19:27
- It's not that easy with generics and/or conditional types typescriptlang./play/?ts=5.6.3#code/… – Alexander Nenashev Commented Nov 19, 2024 at 21:53
1 Answer
Reset to default 0For your example, this is pretty easy with the TypeScript utility type ReturnType
.
type SomeComplexType = {
a: number
}
const fn = (): SomeComplexType[] => {
const result: ReturnType<typeof fn> = [];
// generate result
return result;
};
Playground
Note that this is not a way to get the return type of the "function you are currently in," which I suspect is impossible with arrow functions, and probably should be (you can't call them recursively either).
But because you're assigning it to a named constant, you can access it via that constant.