如何为方括号内的类型参数指定类型? [重复]

问题描述 投票:0回答:1

为什么这个符号是解析错误,或者我应该做什么?我正在尝试将

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 typescript-generics
1个回答
0
投票

问题在于 TypeScript 不支持直接在索引访问类型(如

Foo['myFunc']<string>
)中应用类型参数。

要解决这个问题:

  1. 使用实用程序类型来提取返回类型:

    type MyFuncReturn<T> = Foo['myFunc'] extends (...args: any[]) => T ? T : never;
    type StringFunc = MyFuncReturn<string>;
    
  2. 或者,将

    typeof
    与实例一起使用:

    declare const foo: Foo;
    type StringFunc = ReturnType<typeof foo.myFunc>;
    

这可以避免解析错误并正确绑定泛型类型。

© www.soinside.com 2019 - 2024. All rights reserved.