typescript - get return type of current anonymous function - Stack Overflow

Is there a way in typescript to easily get the return type of the function you're currently in?Eg

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

Share asked Nov 19, 2024 at 18:52 zacajzacaj 2,0851 gold badge24 silver badges40 bronze badges 2
  • 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
Add a comment  | 

1 Answer 1

Reset to default 0

For 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742405028a4437671.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信