概念
type
,全称是 Type Aliases
,即 “类型别名”,注意它是别名而不是真正的类型。
interface (opens new window) 从官网看来可以描述:对象、函数、数组、Class。
交集
测试过程中 interface
的错误提示更友善。
1. interface extends interface
interface Animal {
name: string;
}
interface Dog extends Animal {
say(): string
}
1
2
3
4
5
6
2
3
4
5
6
2. type & type
type Animal = {
name: string;
}
type Dog = Animal & {
say(): string
}
1
2
3
4
5
6
2
3
4
5
6
3. interface extends type
type Animal = {
name: string;
}
interface Dog extends Animal {
say(): string
}
1
2
3
4
5
6
2
3
4
5
6
4. type & interface
interface Animal {
name: string;
}
type Dog = Animal & {
say(): string
}
1
2
3
4
5
6
2
3
4
5
6
区别
1. Tuple
type Tuple = [number, string]
interface ITuple {
0: number
1: string
}
[1, 'hello', false] as Tuple // ERROR
[1, 'hello', false] as ITuple // OK
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2. 合并
type Once = { a: string }
type Once = { b: string }
// Duplicate identifier 'Once'.
interface IOnce {
a: string
}
interface IOnce {
b: string
}
// 合并为
// interface IOnce {
// a: string
// b: string
// }
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
3. 工具类型
type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
1
2
3
2
3