MST

星途 面试题库

面试题:TypeScript中type与interface在定义对象类型时的区别

请详细阐述在TypeScript里,使用type和interface定义对象类型分别有哪些特点及两者之间的区别。同时举例说明在什么场景下会优先选择使用type来定义对象类型,什么场景下会优先选择interface。
21.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

type特点

  1. 灵活定义:type 可以用来定义基本类型别名、联合类型、交叉类型等多种类型。例如定义基本类型别名:
type StringOrNumber = string | number;
  1. 不支持声明合并:重复定义相同名称的 type 会报错。例如:
type Point = { x: number; y: number };
// 再次定义会报错
type Point = { z: number }; 

interface特点

  1. 声明合并:可以多次定义同名的 interface,编译器会将它们合并。例如:
interface Point { x: number; }
interface Point { y: number; }
let p: Point = { x: 1, y: 2 };
  1. 主要用于定义对象类型:interface 专门为定义对象类型而生,语法相对简洁。例如:
interface User { name: string; age: number; }

两者区别

  1. 定义方式:type 使用 type 关键字,interface 使用 interface 关键字。
  2. 适用类型:type 更通用,能定义各种类型;interface 主要用于对象类型定义。
  3. 合并能力:interface 支持声明合并,type 不支持。

优先使用 type 的场景

  1. 定义联合类型或交叉类型:比如定义一个函数参数既可以是字符串又可以是数字的类型。
type Input = string | number;
function printValue(value: Input) {
    console.log(value);
}
  1. 定义基本类型别名:为常用的复杂类型起别名,如函数类型别名。
type MyFunction = (a: number, b: number) => number;
let add: MyFunction = (x, y) => x + y;

优先使用 interface 的场景

  1. 对象类型定义且可能需要声明合并:比如在不同模块中对同一个对象类型进行扩展。
// module1.ts
interface Config { baseUrl: string; }
// module2.ts
interface Config { apiKey: string; }
// main.ts
let config: Config = { baseUrl: 'http://example.com', apiKey: '12345' };
  1. 符合面向对象编程风格定义对象结构:当侧重于描述对象的结构和行为契约时。
interface Shape {
    area(): number;
}
class Circle implements Shape {
    constructor(public radius: number) {}
    area() {
        return Math.PI * this.radius * this.radius;
    }
}