跳至主要内容

type 與 interface

Interface 又是什麼?

跟前一篇 type 的寫法很像:

type
type TUser = {
firstName: string;
lastName: string;
}
const mike: TUser = { firstName: "Mike", lastName: "Cheng" };
interface
interface IUser {
firstName: string;
lastName: string;
}
const mike: IUser = { firstName: "Mike", lastName: "Cheng" };

可以看的出來寫法基本都一樣,可以看到這裡改用 I 來開頭增加易讀性

前面已經學過 type 跟 interface 有什麼差別?

擴充/合併:

  • interface 可以擴充與宣告合併,使用 extends 多個來源
  • type:不可宣告合併;用 & 擴充;可做 union/tuple/條件/映射
type
type TWidth = {
width: string;
}

type THeight = {
height: string;
}

type TBoxFontSize = {
"font-size": string;
"font-weight": string;
}

type TBoxStyle = {
color: string;
border: string;
padding: string;
margin: string;
}
type TBox = TWidth & THeight & TBoxFontSize & TBoxStyle;

const box: TBox = {
width: "100px",
height: "100px",
color: "red",
border: "4px solid #000",
padding: "10px",
margin: "10px",
"font-size": "16px",
"font-weight": "bold",
};
interface
interface IWidth {
width: string;
}

interface IHeight {
height: string;
}

interface IBoxFontSize {
"font-size": string;
"font-weight": string;
}

interface IBoxStyle extends IWidth, IHeight, IBoxFontSize {
color: string;
border: string;
padding: string;
margin: string;
}

const box: IBoxStyle = {
width: "100px",
height: "100px",
color: "red",
border: "4px solid #000",
padding: "10px",
margin: "10px",
"font-size": "16px",
"font-weight": "bold",
};

我要用哪一個?

看團隊習慣或個人喜好

  • type 有 union/tuple/條件/映射型別等能力
    • type name = string
  • interface 專門用來定義物件,可聲明合併(type 不行)
    • interface name {}
    • 只有 interface 可以寫:interface IInfo {name : string}interface IInfo {age: number} 會自動合併,但你會 debug 到死…