MST

星途 面试题库

面试题:TypeScript中类如何实现接口并处理接口继承

假设有一个基础接口`BaseInterface`,包含属性`name: string`,还有一个继承自`BaseInterface`的接口`DerivedInterface`,增加了属性`age: number`。请编写一个TypeScript类`MyClass`,实现`DerivedInterface`,并在类的构造函数中初始化这些属性,同时提供一个方法打印出这些属性的值。
36.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface BaseInterface {
    name: string;
}

interface DerivedInterface extends BaseInterface {
    age: number;
}

class MyClass implements DerivedInterface {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    printProperties() {
        console.log(`Name: ${this.name}, Age: ${this.age}`);
    }
}

你可以通过以下方式测试这个类:

const myObject = new MyClass('John', 30);
myObject.printProperties();