为什么这个符号是解析错误,或者我应该做什么?我正在尝试将
string
类型传递给 Foo.myFunc
。
type Foo = {
myFunc <T> (): T
}
type stringFunc = Foo['myFunc']<string> // Parsing error: ';' expected
这给了我我想要的东西,但很恶心。
declare const foo: Foo
type stringFunc = typeof foo.myFunc<string>
问题在于 TypeScript 不支持直接在索引访问类型(如
Foo['myFunc']<string>
)中应用类型参数。
要解决这个问题:
使用实用程序类型来提取返回类型:
type MyFuncReturn<T> = Foo['myFunc'] extends (...args: any[]) => T ? T : never;
type StringFunc = MyFuncReturn<string>;
或者,将
typeof
与实例一起使用:
declare const foo: Foo;
type StringFunc = ReturnType<typeof foo.myFunc>;
这可以避免解析错误并正确绑定泛型类型。