TypeScript interface 和 type 比較

使用TypeScript的時(shí)候,一定會(huì)遇到interfacetype aliases 的比較。
官方有兩句話Because [an ideal property of software is being open to extension](https://en.wikipedia.org/wiki/Open/closed_principle), you should always use an interface over a type alias if possible.On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go,就是要我們一般情況下使用interface,當(dāng)interface不能滿足我們的需求時(shí),使用type。
下面通過(guò)一些例子來(lái)比較兩者的異同

1. Objects / Functions

兩者都可以用來(lái)描述對(duì)象或函數(shù),但是語(yǔ)法不同。

interface Point {
  x: number;
  y: number;
}

interface SetPoint {
  (x: number, y: number): void;
}
type Point = {
  x: number;
  y: number;
};

type SetPoint = (x: number, y: number) => void;

2. Other Types

interface不同,type也可以用于其他類(lèi)型,例如原始類(lèi)型、聯(lián)合類(lèi)型、元祖類(lèi)型。

// primitive
type Name = string;

// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];

3. Extend 繼承

兩者都可以被繼承,但是同樣的,語(yǔ)法不同。

  • interface extends interface
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }
  • type alias extends type alias
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
  • interface extends type alias
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
  • type alias extends interface
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };

4. Implements 實(shí)現(xiàn)

一個(gè)class對(duì)于interfacetype alias的實(shí)現(xiàn)是一樣的。但是,classinterface被認(rèn)為是靜態(tài)藍(lán)圖(static blueprints),因此,他們不能 Implements / extend 聯(lián)合類(lèi)型的 type alias

interface Point {
    x: number;
    y: number;
}

class SomePoint implements Point {
    x: 1;
    y: 2;
}

type Point2 = {
    x: number;
    y: number;
};

class SomePoint2 implements Point2 {
    x: 1;
    y: 2;
}

type PartialPoint = { x: number; } | { y: number; };
// ? A class can only implement an object type or intersection of object types with statically known members.t
class SomePartialPoint implements PartialPoint {
    x: 1;
    y: 2;
}

4. Declaration Merging (聲明合并)

// These two declarations become:
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

【更多】https://www.typescriptlang.org/docs/handbook/advanced-types.html

【參考】typescript-interfaces-vs-types

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容