MST

星途 面试题库

面试题:TypeScript类与接口结合时的类型兼容性及复杂场景应用

假设有一个接口`IParent`,它有一个属性`name: string`和一个方法`print(): void`。然后有两个类`Child1`和`Child2`都实现了`IParent`接口。现在定义一个函数`handle`,它接受一个实现了`IParent`接口的对象作为参数。如果`Child1`新增了一个私有属性`private extraProp1: number`,`Child2`新增了一个静态方法`static staticMethod(): void`,在`handle`函数中如何正确处理这两个类的实例,同时说明TypeScript在这种类与接口结合的复杂场景下的类型兼容性规则。
48.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

处理函数实现

interface IParent {
    name: string;
    print(): void;
}

class Child1 implements IParent {
    name: string;
    private extraProp1: number;
    constructor(name: string, extraProp1: number) {
        this.name = name;
        this.extraProp1 = extraProp1;
    }
    print() {
        console.log(`Child1 - Name: ${this.name}`);
    }
}

class Child2 implements IParent {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    print() {
        console.log(`Child2 - Name: ${this.name}`);
    }
    static staticMethod() {
        console.log('Child2 static method');
    }
}

function handle(parent: IParent) {
    // 仅处理IParent接口中定义的属性和方法
    parent.print();
    console.log(`Name: ${parent.name}`);

    // 如果需要处理Child1特有的私有属性,这种处理是不被允许直接访问的,因为私有属性只能在类内部访问
    // 如果需要处理Child2特有的静态方法,由于传入的是实例,静态方法无法通过实例调用,需要通过类名调用
    // 所以这里只能处理IParent接口的内容
}

TypeScript类型兼容性规则

  1. 接口实现兼容性:在TypeScript中,只要类实现了接口中定义的所有属性和方法,就满足类型兼容性。Child1Child2都实现了IParent接口中的name属性和print方法,所以它们的实例可以作为参数传递给handle函数,即使Child1有私有属性,Child2有静态方法,这些额外的部分不影响接口兼容性。
  2. 私有属性兼容性:私有属性(如Child1中的extraProp1)仅在类的内部可见。TypeScript的类型系统在检查兼容性时,不会因为类中有私有属性而影响其与接口的兼容性,但外部代码无法直接访问这些私有属性。
  3. 静态成员兼容性:静态成员(如Child2中的staticMethod)不属于实例的类型范畴。接口只描述实例的属性和方法,所以静态方法不会影响类与接口的兼容性。在handle函数中,传入的是实例,不能直接调用静态方法,需要通过类名(如Child2.staticMethod())调用静态方法。