Appearance
交叉类型
将多个类型合并为一个类型,新的类型将具有所有类型的特性,所以交叉类型特别适合对象过多的场景。交叉类型实际上是取所有类型的并集
typescript
interface DogInterface {
run(): void;
}
interface CatInterface {
jump(): void;
}
// pet变量将具有两个接口类型的所有方法
/*
不能将类型“{}”分配给类型“DogInterface & CatInterface”。
类型 "{}" 中缺少属性 "run",但类型 "DogInterface" 中需要该属性。ts(2322)
*/
let pet: DogInterface & CatInterface = {};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typescript
interface DogInterface {
run(): void;
}
interface CatInterface {
jump(): void;
}
// pet变量将具有两个接口类型的所有方法
let pet: DogInterface & CatInterface = {
run() {},
jump() {},
};
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13