说明

从效果上看,type和interface的效果差不多,都能够实现对变量的约束。但是二者在定义和使用上还是存在一些区别的。

使用

首先来从定义的角度来看:

  1. // 定义type
  2. type User = {
  3. user: string;
  4. }
  5. const obj: User = {
  6. user: 'root'
  7. }
  8. // 定义接口
  9. interface UserInterface {
  10. user: string;
  11. }
  12. const obj2: UserInterface = {
  13. user: 'admin'
  14. }

二者一个是通过type关键字一个是通过interface关键字来进行声明。

如果在定义的过程中出现重名的问题,type不允许重名,而interface允许重名。
image.png
出现重名的Type 发生异常。

image.png
如果接口出现重名,则会进行规则的合并。

如果想要合并规则,接口除了接口名相同以外,还可以通过继承的写法来实现。

image.png

type想要实现合并,需要使用到&
image.png

如果在组合type中使用|,则是实现任意一个约束即可。
image.png
在实际的开发过程中,type和接口是可以混用的。
比如:

  1. type User = {
  2. name: string;
  3. }
  4. interface UserInterface {
  5. age: number;
  6. }
  7. class Person implements User, UserInterface {
  8. public name: string;
  9. public age: number;
  10. constructor(name: string, age: number) {
  11. this.name = name;
  12. this.age = age;
  13. }
  14. }

上面代码中类Person同时使用User和UserInterface进行约束。

也可以使用&来将typeinterface进行混用。

  1. type User = {
  2. name: string;
  3. }
  4. interface UserInterface {
  5. age: number;
  6. }
  7. type Person = User & UserInterface;
  8. const obj: Person = {
  9. name: 'John',
  10. age: 30
  11. }

注意

无。

总结

type和interface 二者有很多相似的地方,也有一些区别。具体在开发中到底应该用哪个,主要还是看公司的开发规范和具体的应用场景。