MST

星途 面试题库

面试题:TypeScript交叉类型在复杂对象继承场景下的应用

现有三个接口,`BaseInterface`有属性`id: number`,`ChildInterface1`继承自`BaseInterface`并新增属性`email: string`,`ChildInterface2`继承自`BaseInterface`并新增属性`phone: string`。请通过交叉类型创建一个新类型`MergedType`,使其拥有`id`、`email`和`phone`属性,并编写一个函数,该函数接收`MergedType`类型的参数并打印其中所有属性值。
36.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface BaseInterface {
    id: number;
}

interface ChildInterface1 extends BaseInterface {
    email: string;
}

interface ChildInterface2 extends BaseInterface {
    phone: string;
}

type MergedType = ChildInterface1 & ChildInterface2;

function printProperties(obj: MergedType) {
    console.log(`id: ${obj.id}, email: ${obj.email}, phone: ${obj.phone}`);
}

你可以使用以下方式调用函数:

const testObj: MergedType = {
    id: 1,
    email: "test@example.com",
    phone: "1234567890"
};

printProperties(testObj);