当我有一个具有这样的泛型的接口(interface)时:
interface I1<S> {
a: string;
b: genericType<S>
}
并尝试提取属性类型a
使用I1['a']
, typescript 抛出以下错误:
TS2314: Generic type 'I1<S>' requires 1 type argument(s).
这应该没问题吧,因为提取的属性类型实际上并不依赖于 <S>
?要么我无法理解 Typescript 的实际工作原理,要么这确实应该没问题。
最佳答案
属性a
类型不依赖于S
,但您不能省略类型参数作为 lookup 的一部分。一些选项:
1.) 将S
设置为未知
type T1 = I1<unknown>["a"] // string
2.) 在界面中声明 S
的默认值
interface I2<S = unknown> {
a: string;
b: S
}
type T2 = I2["a"] // string
3.) 保持通用
type T3<S> = I1<S>["a"] // T3<S> = string
// doesn't make too much sense in this particular case
关于typescript - 提取泛型接口(interface)的属性类型仍然需要不必要的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59576819/