是否存在,或者有没有办法能够使用这样的东西:
type X<Obj, FieldType> = ???;
interface A {
a: number;
b: number;
c: string;
d: Date;
}
type Nums = X<A, number>; // == 'a' | 'b'
type Strings = X<A, string>; // == 'c'
type Dates = X<A, Date>; // == 'd'
X
我要查找的泛型类型在哪里(keyof Obj
在本例中为 的子集keyof A
)。
您可以使用条件类型来过滤所需类型的属性:
type X<Obj, FieldType> = {
[P in keyof Obj]-?: Obj[P] extends FieldType ? P : never
}[keyof Obj];
interface A {
a: number;
b: number;
c: string;
d: Date;
}
type Nums = X<A, number>; // == 'a' | 'b'
type Strings = X<A, string>; // == 'c'
type Dates = X<A, Date>; // == 'd'
你可以在这里查看我对此的解释
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句