Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript:如何过滤类型';将属性转换为特定类型的属性?_Typescript - Fatal编程技术网

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"