Interface 和 Type 是用來定義型別的兩種語法,那麼兩者又有什麼區別呢?
Interface 介面
- 主要用於定義 「物件型別」
- 不能直接宣告基本型別、元組、列舉與聯合型別
- 可以重複宣告,支援擴展與合併
擴展(Extends)
假設我們定義了一個 Person 介面
|
接著定義一個新介面,並透過 extends 擴充 Person
|
使用 User 介面的資料,就必須包含 name、age、id、createdAt 參數
|
合併(Merging)
介面可以被重複宣告,以下範例最後結果會是兩者合併
|
Type Aliases 型別別名
- 用來賦予型別一個新的名稱
- 可以直接宣告基本型別、元組、列舉、聯合型別、物件以及複雜型別
- 不可以重複宣告,不支援擴展,但可以透過
&交集來組合型別
宣告型別別名
基本型別
type Num = number;
const num: Num = 123;元組
type Arr = [ string, number ];
const arr: Arr = [ 'Daniel', 18 ];聯合型別
type UserId = number | string;
const userId: UserId = 123;
userId = '123';列舉
enum ColorChart {
Red = 'red',
Blue = 'blue',
Green = 'green'
}
type Color = ColorChart;
const color: Color = ColorChart.Red;物件
type Obj = {
id: number,
name: string
}
const obj: Obj = {
id: 111,
name: 'Daniel'
}Mapped Types
type Person = {
name: string,
age: number,
address: string
};
// 將 Person 型別中各屬性調整為可選
type PartialPerson = {
[K in keyof Person]?: Person[K];
};
交集(Intersection)與聯集(Union)
透過交集(&)或聯集(|)來組合型別
|
不能重複宣告
重複宣告會拋錯
|
Interface & Type 使用時機
Type可以直接定義原始型別、元組、列舉、聯合型別、函式、物件等Interface只能定義物件- 物件並且可以被擴充,使用
Interface可讀性較高,extends語意上也較直觀 - 開發第三方套件,型別定義使用
Interface,使用者能彈性的擴充屬性
參考資源:
https://hackmd.io/@hexschool/rJiN4vCup
https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript
https://blog.logrocket.com/types-vs-interfaces-typescript/
Nuxt3 入門:打造 SSR 專案
評論