interface与type
总结自:https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types
1、都能用来描述对象与函数,只是写法不同
//对象
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、type还可以用来描述原始类型、联合类型以及元组
// primitive type Name = string;// union type PartialPoint = PartialPointX | PartialPointY; // tuple type Data = [number, string];
3、都能实现继承(写法不同),且可交叉继承(interface继承type,type继承interface)
interface继承interface(extends)
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }
type继承type(&)
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
interface继承type (同interface继承interface)
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
type继承interface (同type继承type)
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };
4、类可实现interface与type,方式相同(都是implements)
class与interface都是静态的,因此当type用来描述联合类型时不能被实现
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 type class SomePartialPoint implements PartialPoint { x: 1; y: 2; }
5、interface可被定义多次,且每次定义的属性最后都能合并
// 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 };