返回

揭秘 TypeScript 中 Type 与 Interface 的区别

前端

在 TypeScript 中,类型系统是强类型的,这可以帮助开发人员在代码开发阶段及早发现问题,从而避免运行时错误。Type 和 Interface 是 TypeScript 中定义类型和约束变量的两种方式,虽然它们在许多情况下可以互换使用,但它们之间存在一些重要区别,分别适用于不同的情况。

定义

  • Type: 使用 type 声明,它允许您创建一个新的类型,而不需要继承或实现任何现有的类型。

  • Interface: 使用关键字 interface 声明,它允许您定义一个契约(contract),其他类型可以实现(implement)该契约。

语法

  • Type:
type Name = Type;
  • Interface:
interface Name {
  property: Type;
  method(): Type;
}

继承性

  • Type: type 声明本身没有继承性。

  • Interface: 接口可以继承其他接口。

扩展性

  • Type: type 声明不能被扩展。

  • Interface: 接口可以被扩展。

可扩展性

  • Type: 类型声明本身不可扩展,但是可以将类型分配给另一个类型。

  • Interface: 接口可以被扩展,即可以添加新的属性和方法。

使用场景

  • Type:

    • 定义简单的类型别名,使代码更具可读性和可维护性。

    • 创建联合类型或元组类型。

    • 定义枚举类型。

  • Interface:

    • 定义对象类型的契约,以便其他类型可以实现该契约。

    • 定义类或接口的继承关系。

    • 创建可扩展的类型。

示例

// Type 别名
type StringOrNumber = string | number;

// 联合类型
type Direction = "left" | "right" | "up" | "down";

// 元组类型
type Point = [number, number];

// 枚举类型
enum Color {
  Red,
  Green,
  Blue,
}

// 接口
interface Person {
  name: string;
  age: number;
  greet(): void;
}

// 类实现接口
class Employee implements Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

结论

总的来说,Type 和 Interface 都是 TypeScript 中定义类型和约束变量的有效方式。Type 声明非常适合简单的类型别名、联合类型、元组类型和枚举类型。Interface 非常适合定义对象类型的契约、定义类或接口的继承关系以及创建可扩展的类型。