都可以定义 Objects / Functions
interface 和 type 都可以定义 object 或者 functions 类型,但是语法不同。
Interface
interface Point {x: number;y: number;}interface SetPoint {(x: number, y: number): void;}
Type alias
type Point = {x: number;y: number;};type SetPoint = (x: number, y: number) => void;
其他类型
不像 interface ,type alias 还可以用来定义其他类型比如原始类型、组合类型还有元组类型。
// primitvetype Name = string;// objecttype PartialPointX = { x: number; };type PartialPointY = { y: number; };// uniontype PartialPoint = PartialPointX | PartialPointY;// tupletype Data = [number, string];
Extend
interface 和 type alias 都可以继承,但是语法不同。注意,interface 和 type alias 两者不是互斥的, type 可以扩展 type alias ,反之亦然。
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; };
implements
类可以 implement interace 或 type alias ,但是不能 implement / extent 一个联合类型的 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; };// FIXME: can not implement a union typeclass SomePartialPoint implements PartialPoint {x = 1;y = 2;}
声明合并
interface 可以被定义多次并最终合并成一个 interface , type alias 就不行
// 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 };
选用动机
- 在定义公共 API (如编辑一个库)时使用 interface ,这样可以方便使用者继承接口;
- 在定义组件属性(Props)和状态(State)时,建议使用 type ,因为 type 的约束性更强。
参考文档:
