MST

星途 面试题库

面试题:TypeScript中接口联合与联合接口的基础应用

请举例说明TypeScript中接口联合(interface merging)和联合接口(union types in interfaces)的区别,并编写代码实现一个简单场景,其中分别使用接口联合和联合接口来描述一个可能是字符串或者数字的标识信息。
35.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

接口联合(interface merging)

接口联合指的是当有多个同名接口定义时,TypeScript 会将它们合并为一个接口。合并时,同名接口的成员会被合并到同一个接口中。例如:

interface User {
  name: string;
}
interface User {
  age: number;
}
let user: User = { name: 'John', age: 30 };

在上述代码中,两个 User 接口合并成了一个,最终 User 接口有 nameage 两个属性。

联合接口(union types in interfaces)

联合接口指的是在接口中使用联合类型来表示某个属性可以是多种类型中的一种。例如:

interface Identifier {
  id: string | number;
}
let identifier1: Identifier = { id: '123' };
let identifier2: Identifier = { id: 456 };

在上述代码中,Identifier 接口的 id 属性可以是字符串或者数字。

简单场景实现

// 接口联合实现标识信息
interface Identification {
  type: string;
}
interface Identification {
  value: string | number;
}
let identification: Identification = { type: 'id', value: 123 };

// 联合接口实现标识信息
interface IdentificationUnion {
  id: string | number;
}
let identificationUnion1: IdentificationUnion = { id: 'abc' };
let identificationUnion2: IdentificationUnion = { id: 789 };