MST
星途 面试题库

面试题:TypeScript中接口与类型别名的区别

请详细阐述TypeScript中接口(interface)和类型别名(type alias)在定义方式、功能特性以及使用场景上有哪些区别。
22.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

定义方式

  • 接口(interface):使用interface关键字定义,以大括号包裹成员定义。例如:
interface User {
  name: string;
  age: number;
}
  • 类型别名(type alias):使用type关键字定义,后面跟着类型别名和具体类型定义。例如:
type User = {
  name: string;
  age: number;
};

功能特性

  • 接口(interface)
    • 可以重复声明,声明会自动合并。例如:
interface User {
  name: string;
}
interface User {
  age: number;
}
// User接口现在有name和age属性
- 只能用于对象类型的定义,主要为对象的形状进行描述。
- 可以实现extends继承,用于扩展已有接口。例如:
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}
  • 类型别名(type alias)
    • 不能重复声明,重复声明会报错。
    • 可以定义任意类型,包括基本类型、联合类型、交叉类型等。例如:
type ID = number | string;
type Combin = {name: string} & {age: number};
- 可以使用`&`进行交叉类型扩展,类似于接口的继承但语法不同。例如:
type Animal = {
  name: string;
};
type Dog = Animal & {
  breed: string;
};

使用场景

  • 接口(interface)
    • 当定义对象类型且可能需要多次声明合并时,使用接口更合适,例如在大型项目中对不同模块中同一个对象类型的补充定义。
    • 希望使用继承来清晰描述类型层次结构时,接口的extends语法更直观,适用于面向对象编程风格。
  • 类型别名(type alias)
    • 定义非对象类型,如联合类型、交叉类型或基本类型别名时,类型别名更为方便。
    • 当只需要定义一个类型且不会重复声明,尤其是复杂类型组合时,类型别名简洁明了。