1. 问题
type Foo = {
name: string
age: string
}
type Bar = {
name: string
age: string
gender: number
}
type a = keyof Foo | keyof Bar
type b = keyof Foo & keyof Bar
今天在做**type-challenges**
时,发现个自己之前忽略得东西,那就是**&**
和**|**
有什么不同
2. 类型key中
上面**a,b**
答案是这样得,我们发现|会取到所有得**key**
,&只能取到共有得**key**
type a = keyof Foo | keyof Bar // name,age,gender
type b = keyof Foo & keyof Bar // name,age
3. 类型中
这个时候我们发现,**&**
却是取到得两个类型共有成为一个新得集合,而**|**
则是变成了两个类型得联合
type a = Foo | Bar
type b = Foo & Bar
type test<T> = {
[k in keyof T]: T[k]
}
type c = test<a>
type d= test<b>
// type c = test<a> | test<b>
// type d = {
// name: string;
// age: string;
// gender: number;
// }
!!!上述的两个方法换成**interface**
结果也是一样的