最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论