Typescript:如何过滤类型';将属性转换为特定类型的属性?
我有一个接口Typescript:如何过滤类型';将属性转换为特定类型的属性?,typescript,Typescript,我有一个接口 export interface MyInterface { a: number; b: string; c: number; } 我想创建一个属性名的文本类型,其值的类型为number 我知道如何使用 type MyType = keyof MyInterface // gives 'a'|'b'|'c' 我只想得到“a”|“c”不要认为你可以按类型选择属性,但如果你知道你接受的属性,你可以根据这些属性创建一个新类型 type MyType=Pick
export interface MyInterface {
a: number;
b: string;
c: number;
}
我想创建一个属性名的文本类型,其值的类型为number
我知道如何使用
type MyType = keyof MyInterface // gives 'a'|'b'|'c'
我只想得到“a”|“c”不要认为你可以按类型选择属性,但如果你知道你接受的属性,你可以根据这些属性创建一个新类型
type MyType=Pick
我喜欢它涵盖了您可以使用的大多数类型(Readonly
,Partial
,Required
,Pick
,Record
,Extract
,Exclude
等),但我知道最近也引入了省略
我发现这个答案能更好地解释它 您当然可以在TypeScript中定义这样的类型:
type KeysMatching<T extends object, V> = {
[K in keyof T]-?: T[K] extends V ? K : never
}[keyof T];
type MyType = KeysMatching<MyInterface, number>;
// type MyType = "a" | "c"
如果在编写T
的属性时,希望获得与V
匹配的键。。。也就是说,确切地说是V
或V
的超类型,那么您需要一个不同的键匹配实现:
type KeysMatchingWrite<T extends object, V> = {
[K in keyof T]-?: [V] extends [T[K]] ? K : never
}[keyof T];
type AnotherTypeWrite = KeysMatchingWrite<AnotherInterface, number>;
// type AnotherTypeWrite = "exact" | "wider"
键入KeysMatchingWrite={
[K]扩展[T[K]]?K:从不
}[keyof T];
键入另一个typewrite=KeysMatchingWrite您不能。您需要为此创建一个单独的接口。您可以为a | c
创建一个接口,然后创建另一个接口,用b
对其进行扩展。这个接口可能重复!真是太神奇了。我将删除我的答案。在您的类型定义中,我可以从哪里了解更多关于-
的信息?请参阅;它将删除可能存在的任何可选修改器,以避免在键列表中获得未定义的
type KeysMatchingWrite<T extends object, V> = {
[K in keyof T]-?: [V] extends [T[K]] ? K : never
}[keyof T];
type AnotherTypeWrite = KeysMatchingWrite<AnotherInterface, number>;
// type AnotherTypeWrite = "exact" | "wider"