TS中interface
(接口)和type
(类型别名)有许多相似之处:
- 理论开发中两者都能够用来束缚变量的类型
- 两者都能够扩大
- 接口和类型别名不是互斥的,接口能够扩大类型别名,反之亦然
上面次要来看下区别
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
)还能够用于其余类型,如根本类型(原始值)、联结类型、元组
// primitivetype Name = string;// uniontype PartialPoint = PartialPointX | PartialPointY;// tupletype Data = [number, string];// domlet div = document.createElement('div');type B = typeof div;
3、扩大时语法不同,且interface
无奈扩大联结类型的type
interface PartialPointX { x: number; }interface Point extends PartialPointX { y: number; }
type PartialPointX = { x: number; };type Point = PartialPointX & { y: number; };
type PartialPoint = { x: number; } | { y: number; };// 报错:无奈实现一个联结类型的type// class SomePartialPoint implements PartialPoint {// x: 1;// y: 2;// }
4、interface
能够定义屡次,并将被视为单个接口(合并所有申明的成员);type
不能够
interface Point { x: number; }interface Point { y: number; }const point: Point = { x: 1, y: 2 };
5、interfac能够extends
class,class也能够implements
interface
class Point { x: number; y: number;}interface Point3d extends Point { z: number;}
interface Foo { name: string; age: number; sayHello(): void;}class Bar implements Foo { name: string; age: number; sayHello(): void { console.log('Hello'); }}
6、type
反对计算属性,生成映射类型,interface
不能够
type
能应用in
关键字生成映射类型,但interface
不行- 语法与索引签名的语法类型,外部应用了
for .. in
type Keys = "firstname" | "surname"type DudeType = { [key in Keys]: string}const test: DudeType = { firstname: "Pawel", surname: "Grzybek"}// 报错//interface DudeType2 {// [key in keys]: string//}
总结:我平时开发中,习惯在一个module下新建一个公共文件interface.ts
,专门export各种interface,用于束缚以后module业务代码中各种变量的类型和取值范畴;如果独自某个组件中的变量取值范畴比拟非凡,那就在其组件业务代码中用type束缚下