面试题答案
一键面试接口联合(interface merging)
接口联合指的是当有多个同名接口定义时,TypeScript 会将它们合并为一个接口。合并时,同名接口的成员会被合并到同一个接口中。例如:
interface User {
name: string;
}
interface User {
age: number;
}
let user: User = { name: 'John', age: 30 };
在上述代码中,两个 User
接口合并成了一个,最终 User
接口有 name
和 age
两个属性。
联合接口(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 };