打字稿如何创建具有两种类型共同属性的类型? [英] Typescript how to create type with common properties of two types?
本文介绍了打字稿如何创建具有两种类型共同属性的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有两种类型
type A = {
x: number
y: number
}
type B = {
y: number
z: number
}
如何获取具有该类型通用属性的类型?
How to get type with common properties of that types?
type C = Something<T1, T2> // { y: number }
推荐答案
通用属性
使用静态keyof
操作符:
type Ka = keyof A // 'x' | 'y'
type Kb = keyof B // 'y' | 'z'
type Kc = Ka & Kb // 'y'
并在 Kc 中定义具有属性的 映射类型代码>:
type C = {
[K in keyof A & keyof B]: A[K] | B[K]
}
这定义了一种新类型,其中每个键都将出现在 A
和 B
中.
This defines a new type where each key will be present both in A
and B
.
与此键关联的每个值的类型为 A[K] |B[K]
,以防A[K]
和B[K]
不同.
Each value associated to this key will have type A[K] | B[K]
, in case A[K]
and B[K]
are different.
使用条件类型来映射键仅当 A 和 B 中的类型相同时才取值:
Use Conditional Type to map key to value only if type same in A and B:
type MappedC = {
[K in keyof A & keyof B]:
A[K] extends B[K] // Basic check for simplicity here.
? K // Value becomes same as key
: never // Or `never` if check did not pass
}
从这个对象中,通过访问所有键获得所有值的联合:
From this object, get union of all values, by accessing all keys:
// `never` will not appear in the union
type Kc = MappedC[keyof A & keyof B]
最后:
type C = {
[K in Kc]: A[K]
}
这篇关于打字稿如何创建具有两种类型共同属性的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文