背景
TypeScript中的 interface 和 type 都是声明自定义类型的方式,但它们有一些区别,适用于不同的使用场景。
两者使用案例
interface
interface 主要用于描述对象的形状或者类的结构,这是它最经常的应用场景。
interface使用示例:
interface Person {name: string;age: number;
}function greet(person: Person) {return 'Hello, ' + person.name;
}let user = {name: 'Jack', age: 20};console.log(greet(user));在这个例子中,我们定义了一个 Person 接口,它有两个属性,名字和年龄。然后我们创建了一个函数 greet,它接收一个 Person 类型的参数。最后,我们创建了一个 user 对象并调用了 greet 函数。this example avoided passing an object that didn’t meet the Person interface structure to the greet function.
type
type 更概括一点,它除了可以用于描述对象的形状,还可以用于其他种类的类型设置,例如原始类型(primitive),联合类型(union),交叉类型(intersection),元组等。
type使用示例:
声明一个只有名字的类型:
type Name = string;let name: Name = 'Tom';声明一个联合类型:
type StringOrNumber = string | number;let input: StringOrNumber;input = 'Tom'; // OK
input = 20;  // OK
input = true;  // Error两者具体区别
- interface更专注于定义对象或类的结构,而- type更通用。
- interface可以被实现(implements)和扩展(extends),但是- type不可以。
- interface可以被声明合并,如果多次声明同一个- interface,那么它们会被自动合并,当- type不具备声明合并的特性。
根据上述差异,选择使用 interface 还是 type 就基于具体的业务需求。在大部分情况下,如果仅仅是为了类型检查,interface 和 type 都可以满足需求,然而如果需要进行 OOP (Object Oriented Programming) 的实践,如类的定义与继承,则 interface 会更加合适一些。