使用TypeScript的時候,一定會遇到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荸实,當interface不能滿足我們的需求時工坊,使用type蜗帜。
下面通過一些例子來比較兩者的異同
1. Objects / Functions
兩者都可以用來描述對象或函數越妈,但是語法不同。
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
也可以用于其他類型梅掠,例如原始類型、聯合類型店归、元祖類型阎抒。
// 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 繼承
兩者都可以被繼承,但是同樣的消痛,語法不同且叁。
- 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 實現
一個class
對于interface
和type alias
的實現是一樣的。但是秩伞,class
和interface
被認為是靜態(tài)藍圖(static blueprints)逞带,因此欺矫,他們不能 Implements / extend
聯合類型的 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