导航
×
   ❮   
HTML CSS JavaScript PHP Python C C++ Go Sass W3C Colors TypeScript ECMS

TypeScript 类型别名和接口


TypeScript 允许类型被独立于使用它们的变量进行定义。

别名和接口允许类型在不同的变量/对象之间轻松共享。


类型别名 (Type Aliases)

类型别名允许使用自定义名称 (一个别名) 来定义类型。

类型别名可以用于原始类型,如 string,或者更复杂的类型,如 objects 和 arrays。

实例

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
};
亲自试一试 »

接口

接口 (Interfaces) 与类型别名类似,但它们仅适用于 object 类型。

实例

interface Rectangle {
  height: number,
  width: number
}

const rectangle: Rectangle = {
  height: 20,
  width: 10
};
亲自试一试 »

扩展接口 (Extending Interfaces)

接口可以扩展彼此的定义。

扩展一个接口意味着创建一个新接口,它包含原始接口的所有属性,并增加新的属性。

实例

interface Rectangle {
  height: number,
  width: number
}

interface ColoredRectangle extends Rectangle {
  color: string
}

const coloredRectangle: ColoredRectangle = {
  height: 20,
  width: 10,
  color: "red"
};
亲自试一试 »

Copyright ©2026 蒙ICP备2026009383号 All Rights Reserved 提供的内容仅用于学习和测试,不保证内容的正确性。