深入理解 TypeScript 的 type ,以及 type 与 interface 的区别

65 阅读3分钟

1.type

type 是 TypeScript 中用于定义类型别名、联合类型、交叉类型等复杂类型的声明方式。它在编译后的 JavaScript 代码中被移除,因为它们仅在编译阶段用于类型检查。换句话说,type 不需要运行时信息。

  • 类型别名(Type Aliases):类型别名是给一个类型起一个新名字。例如:
  type StringOrNumber = string;
  • 联合类型(Union Types):联合类型表示一个值可以是多个类型中的一种。例如:
  type StringOrNumber = string | number;
  • 交叉类型(Intersection Types):交叉类型表示一个值必须满足多个类型的要求。例如:
  type Name = { name: string }; 
  type Age = { age: number }; 
  type Person = Name & Age;
  • 不需要运行时信息:在 TypeScript 中,有些类型信息仅在编译时起作用,而在运行时则不存在。例如,type 和 interface 定义的类型信息在编译后的 JavaScript 代码中被移除,因为它们仅在编译阶段用于类型检查。相比之下,class 定义的类型信息会保留在编译后的代码中,因为它们包含实际的属性和方法实现,这些信息在运行时是必需的。

2.interface

interface 仅限于描述对象类型。它支持继承和实现,因此非常适合创建复杂的对象类型。和 type 一样,interface 定义的类型信息在编译后的代码中被移除。 interface 可以通过关键字 extends 实现接口继承,通过关键字 implements 实现接口实现。这让我们可以创建具有多层次的类型结构。

例如:

interface Animal {  name: string;  speak(): void;}
interface Dog extends Animal {  breed: string;}

class Labrador implements Dog {
name: string;  breed: string;
  constructor(name: string, breed: string) { 
  this.name = name; 
  this.breed = breed; 
  }
  speak() { 
  console.log(`${this.name} says woof!`); 
  }
}

不同之处

1、type 可以做到而 interface 不能做到
type 可以声明基本类型。 type userName = string;
type 可以声明联合类型。 type userMsg = string | number;
type 可以声明元组类型。 type Data = [number, string];
type 可以通过 typeof 操作符来声明 type myType = typeof someObj;

2、interface 可以做到而 type 不能做到
interface 可以声明合并。

interface test {
name: string
}  
interface test {
age: number
}
/*
test实际为 {
    name: string
    age: number
}
*/  

如果是 type 的话,就会报重复定义的警告,因此是无法实现声明合并的。

使用建议

1、官方推荐使用 interface,其他无法满足需求的情况下用 type。但是因为联合类型和交叉类型是比较常用的,所以避免不了大量使用 type 的场景,一些复杂类型也需要通过组装后形成类型别名来使用。

2、如果想保持代码统一,还是可选择使用 type。通过上面的对比,type 其实可涵盖 interface 的大部分场景。

3、对于 React 组件中 props 及 state,推荐使用 type,这样能够保证使用组件的地方不能随意在上面添加属性。如果有自定义需求,可通过 HOC(高阶组件)二次封装。

4、编写三方库时使推荐使用 interface,其更加灵活自动的类型合并可应对未知的复杂使用场景。

总结:

在 TypeScript 中,typeinterfaceclass 分别具有自己的用途和特点。

  • type 适用于定义类型别名、联合类型、交叉类型等,并且不需要运行时信息。
  • interface 主要用于定义对象的类型和形状,支持继承和实现。

虽然 typeinterface 在很多场景下可以互换使用,但它们在某些特定场景下有着各自的优势。type 更适用于组合不同类型,如联合类型、交叉类型等,而 interface 更适用于定义对象的形状,特别是在面向对象编程中。

在实践中,我们应该根据实际需求和场景选择合适的类型声明方式。例如,在定义一个复杂的对象类型时,可以使用 interface;在组合不同类型时,可以使用 type

原文链接:【xie.infoq.cn/article/1f0…】。