gpt4 book ai didi

泛型函数的Typescript ReturnType

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:25 25 4
gpt4 key购买 nike

TypeScript 2.8 中的新ReturnType是一项非常有用的功能,可让您提取特定函数的返回类型。

function foo(e: number): number {
return e;
}

type fooReturn = ReturnType<typeof foo>; // number

但是,我在通用函数的上下文中使用它时遇到了问题。

function foo<T>(e: T): T {
return e;
}

type fooReturn = ReturnType<typeof foo>; // type fooReturn = {}

type fooReturn = ReturnType<typeof foo<number>>; // syntax error

type fooReturn = ReturnType<(typeof foo)<number>>; // syntax error

有没有办法提取泛型函数给特定类型参数的返回类型?

最佳答案

这是我目前用于提取未导出的导入库(如 knex)的内部类型的解决方案:

// foo is an imported function that I have no control over
function foo<T>(e: T): InternalType<T> {
return e;
}

class Wrapper<T> {
// wrapped has no explicit return type so we can infer it
wrapped(e: T) {
return foo<T>(e)
}
}

type FooInternalType<T> = ReturnType<Wrapper<T>['wrapped']>
type Y = FooInternalType<number>
// Y === InternalType<number>

关于泛型函数的Typescript ReturnType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50321419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com