TS 别名 &接口
创建于 2024-12-03 /
26
字体:
[默认]
[大]
[更大]
TypeScript 允许将类型与使用它们的变量分开定义。
别名和接口允许在不同的变量/对象之间轻松共享类型。
类型别名
类型别名允许使用自定义名称(别名)定义类型。
类型别名可用于 string
等原语或更复杂的类型,如 objects
和 数组
:
实例
type CarYear = numbertype 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"
}; 亲自试一试 »
TypeScript 练习
0 人点赞过