前言
如果 type 和 interface 都可以使用的时候,应该怎么使用?
一般情况下,如果和对象相关的,会使用 interface ,不和对象相关使用 type。
区别
概念不同
type 指的是类型别名,是 ts 高级类型 的一种。而 interface 指的是 接口。
范围不同
type 适用于基础类型,但 interface 不适用。比如
type A = string;
是否会创建新的类型
interface 是会创建一个新的类型的,但 type 不会,type 只是创建类型别名,不会创建新的类型。
组合方式不同
type 和 interface 都可以进行类型的组合使用,但是组合的方式不同。
interface 使用继承来实现组合,type 使用交叉类型来进行组合。
// interfaceinterface B {b: string}interface A extends B {a: string}const a: A = {a: "123",b: "456"}
// typetype B = {b: string}type A = {a: string} & Bconst a: A = {a: "123",b: "456"}
是否能重复声明不同
interface 可以重复声明,而且重复声明会进行叠加。但 type 不能重复声明,只能声明一次。
interface A {a: string}interface A {aa: string}const a: A = {a: "hi",aa: "hi"}
type A = {a: string}type A = {aa: string} // 报错 Duplicate identifier 'A'
