TypeScript 类型别名和接口
TypeScript 允许将类型与使用它们的变量分开定义。
别名和接口允许在不同的 变量/对象 之间轻松共享类型。
类型别名
类型别名可以使用自定义名称(别名)定义类型。
Type Aliases can be used for primitives like string or more complex types such as objects and arrays
类型别名可用于 字符串 等基础或更复杂的类型,如 对象 和 数组:
// 尝试使用提供的别名创建一辆新的车辆type CarYear = number;type CarType = string;type CarModel = string;type Car = {year: CarYear,type: CarType,model: CarModel};const carYear: CarYear = 2001const carType: CarType = "Toyota"const carModel: CarModel = "Corolla"const car: Car = {year: carYear,type: carType,model: carModel};console.log(car);
接口
接口与类型别名类似,只是它们仅适用于 对象 类型:
// 尝试使用下面的接口创建一个新接口interface Rectangle {height: number,width: number};const rectangle: Rectangle = {height: 20,width: 10};console.log(rectangle);
扩展接口
接口可以扩展。
扩展一个接口意味着您正在创建一个新接口,该接口具有与原始接口相同的属性,以及一些新的属性。
// 尝试创建一个新的接口并扩展它,如下所示interface Rectangle {height: number,width: number}interface ColoredRectangle extends Rectangle {color: string}const coloredRectangle: ColoredRectangle = {height: 20,width: 10,color: "red"};console.log(coloredRectangle);