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"
};
自己動手試一試 »