提取通用接口的属性类型仍然需要不必要的通用类型
Extracting types of properties of generic interfaces still requires unnecessary generic type
当我有这样一个泛型接口时:
interface I1<S> {
a: string;
b: genericType<S>
}
并尝试使用 I1['a']
提取 属性 a
的类型,打字稿会抛出以下错误:
TS2314: Generic type 'I1<S>' requires 1 type argument(s).
这不是很好吗,因为提取的 属性 类型实际上并不依赖于 <S>
?要么我不明白 Typescript 是如何工作的,要么这应该没问题。
属性 a
类型不依赖于 S
,但您不能省略类型参数作为 lookup 的一部分。部分选项:
1.) 将 S
设置为 unknown
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
应该是:
interface I1<S> {
a: string;
b: S;
}
并且制作对象时需要给出S的类型:
请注意,我在下面为 S 泛型类型参数提供了字符串类型,但这可以是您希望 "b" 成为的任何类型。
const i1object: I1<string> = { a: "a", b: "b" };
const i1object2: I1<number> = { a: "a", b: 5 };
当我有这样一个泛型接口时:
interface I1<S> {
a: string;
b: genericType<S>
}
并尝试使用 I1['a']
提取 属性 a
的类型,打字稿会抛出以下错误:
TS2314: Generic type 'I1<S>' requires 1 type argument(s).
这不是很好吗,因为提取的 属性 类型实际上并不依赖于 <S>
?要么我不明白 Typescript 是如何工作的,要么这应该没问题。
属性 a
类型不依赖于 S
,但您不能省略类型参数作为 lookup 的一部分。部分选项:
1.) 将 S
设置为 unknown
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
应该是:
interface I1<S> {
a: string;
b: S;
}
并且制作对象时需要给出S的类型:
请注意,我在下面为 S 泛型类型参数提供了字符串类型,但这可以是您希望 "b" 成为的任何类型。
const i1object: I1<string> = { a: "a", b: "b" };
const i1object2: I1<number> = { a: "a", b: 5 };