使用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
被认为是静态蓝图(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