组合类型
# 前言
前面我们学习了TypeScript中定义基本类型的几种方式,但是仅仅是这样是完全发挥不出TypeScript真正的优势的,而将不同的类型组合起来,可操作性更好,所以TypeScript也提出了组合类型的概念。
# 基本使用
interface Me {
name: string,
hobby: string
}
interface Other {
name: string,
hobby: string
}
// 类似这样使用
let person: Me | Other;
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 联合
定义接口
// 定义错误处理的公共接口
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtworksData {
artworks: { title: string }[];
}
interface ArtistsData {
artists: { name: string }[];
}
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
使用&
关键字定义类型:
type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;
1
2
2
然后可以这样使用:
const handleArtistsResponse = (response: ArtistsResponse) => {
if (response.error) {
console.error(response.error.message);
return;
}
console.log(response.artists);
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
编辑 (opens new window)
上次更新: 2021/05/21, 10:37:31