使用TypeScript的時(shí)候,一定會(huì)遇到interface 和 type 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ì)于interface和type alias的實(shí)現(xiàn)是一樣的。但是,class和interface被認(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