【发布时间】:2020-11-15 18:00:24
【问题描述】:
我很确定 TypeScript 有办法做到这一点,但我还没有弄清楚。
有没有办法从typeof泛型函数中提取泛型类型?
考虑这个简单的泛型函数:
function echo<T> (input: T) {
return input;
}
我想提取这个函数的泛型。我试过了:
type IEchoFn = typeof echo;
但它无法使用:
const echo2: IEchoFn = (input: string) => input;
^^^^^
// Type '(input: string) => string' is not
// assignable to type '<T>(input: T) => T'.
我想我会把它写成
type IEchoFn<T> = (typeof echo)<T>;
但这是无效的语法。
如何从typeof 一个泛型函数(或其返回值)中提取泛型类型?
【问题讨论】:
-
您可以将通用函数分配给具体函数,但不能反过来。这会起作用:
const echo2: (input: string) => string = echo; -
我也遇到了同样的问题。通常,我们使用具有复杂模板类型的函数的包。通常使用
typeof fn是有利的,但是如果没有分配模板类型的方法,我们就不能使用typeof。它会导致一些非常难看的打字。 -
github上的相关问题:github.com/microsoft/TypeScript/issues/37181
标签: typescript generics