【TypeScript】Interface 與 Type 的差異
Published in
3 min readSep 11, 2020
🚩 前言
這篇主要的重點在於講解 Interface
與 Type
的差異,
雖然在使用上看起來真的超像,
但是 Type
是屬於靜態的資料格式,
他無法像 Interface
可以延展(使用 extends
)。
🚩 Interface
interface IPokémonType {
strongAgainst: string[],
weakAgainst: string[],
resistantTo: string[],
vulnerableTo: string[]
}
interface IPokémonBasic {
name: string,
weight: number,
birth: string
}
interface IMyPokémon extends IPokémonType, IPokémonBasic {
nickname? : string
}
這段 code
的意思用中文來解釋是:
想要實作出 IMyPokémon
介面時,
除了要符合 IMyPokémon
本身的屬性與功能之外,
還必需符合 IPokémonType
與 IPokémonBasic
的介面定義出來的屬性與功能。
🚩 Type
type TPokémonType = {
strongAgainst: string[],
weakAgainst: string[],
resistantTo: string[],
vulnerableTo: string[]
}
type TPokémonBasic = {
name: string,
weight: number,
birth: string
}
type TMyPokémon = TPokémonType & TPokémonBasic;
這段 code
的意思用中文來解釋是:TMyPokémon
的靜態資料格式為TPokémonType
與 TPokémonBasic
所組成的。
🚩 總結
今天我有一隻皮卡丘,
在宣告變數的時候會如下:
const IMyPikachu: myPokémon = {
type: 'electronic',
strongAgainst: ['Flying', 'Water'],
weakAgainst: ['Ground', 'Grass', 'Electric', 'Dragon'],
resistantTo: ['Flying', 'Steel', 'Electric'],
vulnerableTo: ['Ground'],
name: 'pikachu',
weight: 20,
birth: '2020/09/11',
nickname: '皮神'
}
我的寶可夢除了有最基本的 IPokémonType
代表電氣、強於飛行系 ... 之類的,
還有 IPokémonBasic
代表他的基本資料,
使用 Interface
就能夠展延 IPokémonType
、IPokémonBasic
,
還能夠擁有 IMyPokémon
本身的屬性與功能 nickname
。