面试题答案
一键面试// 定义基础接口
interface BaseInterface {
name: string;
age: number;
}
// 定义子接口ChildInterface1
interface ChildInterface1 extends BaseInterface {
email: string;
}
// 定义子接口ChildInterface2
interface ChildInterface2 extends BaseInterface {
phone: string;
}
// 定义接收同时满足ChildInterface1和ChildInterface2的对象的函数
function printAllProperties(obj: ChildInterface1 & ChildInterface2) {
console.log(`name: ${obj.name}`);
console.log(`age: ${obj.age}`);
console.log(`email: ${obj.email}`);
console.log(`phone: ${obj.phone}`);
}
你可以使用以下方式调用这个函数:
let testObj: ChildInterface1 & ChildInterface2 = {
name: "张三",
age: 30,
email: "zhangsan@example.com",
phone: "12345678901"
};
printAllProperties(testObj);
以上代码在TypeScript环境下实现了题目要求。首先定义了基础接口BaseInterface
,接着通过extends
关键字分别创建了ChildInterface1
和ChildInterface2
子接口,然后定义了接收同时满足两个子接口的对象的函数printAllProperties
,并在函数内部打印出所有属性。最后创建了一个符合条件的对象并调用函数进行测试。
如果是在JavaScript环境下,可以按照以下方式实现:
// 定义接收对象的函数
function printAllProperties(obj) {
console.log(`name: ${obj.name}`);
console.log(`age: ${obj.age}`);
console.log(`email: ${obj.email}`);
console.log(`phone: ${obj.phone}`);
}
let testObj = {
name: "张三",
age: 30,
email: "zhangsan@example.com",
phone: "12345678901"
};
printAllProperties(testObj);
JavaScript中没有接口的概念,通过对象字面量和函数实现了类似的功能,同样接收包含所需属性的对象并打印出属性值。