MST
星途 面试题库

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

请阐述在TypeScript中接口(interface)和类型别名(type alias)在定义、使用场景及功能上有哪些区别,并各举一个实际的代码示例。
39.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

定义区别

  • 接口(interface):使用 interface 关键字定义,主要用于定义对象的形状(shape),对对象结构进行约束。它只能用于定义对象类型相关结构。
interface User {
  name: string;
  age: number;
}
  • 类型别名(type alias):使用 type 关键字定义,可以为任意类型创建别名,包括基本类型、联合类型、交叉类型等。
type StringOrNumber = string | number;

使用场景区别

  • 接口(interface)
    • 当需要定义对象的公共结构,尤其是在面向对象编程中,用于对象类型的描述和契约定义时使用。比如定义函数参数对象的结构、类实现的契约等。
    function greet(user: User) {
      console.log(`Hello, ${user.name}! You are ${user.age} years old.`);
    }
    const tom: User = { name: 'Tom', age: 25 };
    greet(tom);
    
  • 类型别名(type alias)
    • 用于创建通用类型别名,比如联合类型、交叉类型的别名,增强代码可读性。还可以为函数类型定义别名。
    type Callback = () => void;
    function execute(callback: Callback) {
      callback();
    }
    function sayHello(): void {
      console.log('Hello!');
    }
    execute(sayHello);
    

功能区别

  • 接口(interface)
    • 支持声明合并,即多个同名接口声明会自动合并为一个接口。
    interface Point {
      x: number;
    }
    interface Point {
      y: number;
    }
    const p: Point = { x: 1, y: 2 };
    
  • 类型别名(type alias)
    • 不支持声明合并。但类型别名可以通过交叉类型实现类似接口合并部分功能。
    type A = { a: string };
    type B = { b: number };
    type AB = A & B;
    const ab: AB = { a: 'test', b: 1 };