TypeScript 类型别名和接口
TypeScript 允许类型与使用它们的变量分开定义。
别名和接口允许在不同变量/对象之间轻松共享类型。
类型别名
类型别名允许使用自定义名称(别名)定义类型。
类型别名可用于像 string 这样的基本类型,或者像 object 和 array 这样更复杂的类型:
实例
type CarYear = number
type CarType = string
type CarModel = string
type Car = {
year: CarYear,
type: CarType,
model: CarModel
}
const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla"
const car: Car = {
year: carYear,
type: carType,
model: carModel
};
接口
接口类似于类型别名,但只适用于 object 类型。
实例
interface Rectangle {
height: number,
width: number
}
const rectangle: Rectangle = {
height: 20,
width: 10
};
扩展接口
接口可以扩展其他接口的定义。
扩展接口意味着您正在创建一个具有与原始接口相同属性的新接口,并添加了一些新内容。
实例
interface Rectangle {
height: number,
width: number
}
interface ColoredRectangle extends Rectangle {
color: string
}
const coloredRectangle: ColoredRectangle = {
height: 20,
width: 10,
color: "red"
};