MST
星途 面试题库

面试题:TypeScript接口继承中extends关键字的应用

假设有一个基础接口`BaseInterface`,包含属性`name`和`age`,请通过`extends`关键字创建两个子接口`ChildInterface1`和`ChildInterface2`,`ChildInterface1`增加`email`属性,`ChildInterface2`增加`phone`属性。然后创建一个函数,该函数接收一个同时满足`ChildInterface1`和`ChildInterface2`的对象作为参数,并在函数内部打印出所有属性。
27.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义基础接口
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关键字分别创建了ChildInterface1ChildInterface2子接口,然后定义了接收同时满足两个子接口的对象的函数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中没有接口的概念,通过对象字面量和函数实现了类似的功能,同样接收包含所需属性的对象并打印出属性值。