type与interface相同点
关键字type与interface都可以用来描述对象或者函数
1. 定义对象
// type 定义对象
type Book {
name: string,
publish: number
}
// interface定义对象
interface Book {
name: string,
publish: number
}
2. 函数签名
// type定义函数签名
type SetBook = (name: string, publish: number): Book | void
// interface 定义函数签名
interface SetBook {
(name: string, publish: number): void
}
type与interface不同点
1. type可以声明基本数据类型别名/联合类型/元组等,而interface不行
// 基本类型别名
type UserName = string;
type UserName = string | number;
// 联合类型
type Animal = Pig | Dog | Cat;
2. type可以通过&运算进行交叉操作,而interface不行
type Animal = {
name: string
}
interface Animal2 {
name2: string
}
// type与type交叉
type Dog = Animal & {
size: number
}
// type与interface交叉
type Dog = Animal2 & {
size: number
}
3. interface允许extends或者implement,而type不行
interface Animal {
name: string
}
interface Dog extends Animal {...}
4. interface能够合并声明,而type不行
interface Dog {
name: string
}
interface Dog {
size: number
}
// 此时Dog同时具有name和size属性
网友评论