You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据TypeScript类实例类型调用对应公共方法?

解决TypeScript中根据子类类型调用对应方法的问题

方案一:使用类型断言快速适配现有代码

你可以通过类型断言告诉TypeScript当前person实例的具体子类类型,直接调用对应方法。修改循环部分的代码即可:

for(let person of persons){
    let typeOfPerson = Object.getPrototypeOf(person).constructor.name;
    switch (typeOfPerson) {
        case "Man":
            (person as Man).helloMan();
            break;
    
        case "Woman":
            (person as Woman).helloWoman();
            break;
    
        default:
            break;
    }
}

不过这种方式依赖类的名称字符串,一旦类名修改就会出错,而且不够符合面向对象的设计原则。


方案二:抽象方法+多态(更规范的面向对象实现)

更好的方式是在抽象基类Person中定义一个抽象的hello方法,让子类各自实现这个方法,这样不需要判断类型,直接调用统一的方法即可,符合多态特性:

修改后的完整代码:

abstract class Person {
    static population: number = 0;
    constructor() {
        Person.population ++ ;
    }
    // 定义抽象方法,子类必须实现
    abstract hello(): void;
}

class Man extends Person {
    age!: number;

    constructor(age: number) {
        super();
        this.age = age;
    }

    // 实现抽象方法
    public hello() {
        console.log('Hello Man!');
    }
}

class Woman extends Person {
    age!: number;

    constructor(age: number) {
        super();
        this.age = age;
    }

    // 实现抽象方法
    public hello() {
        console.log('Hello Woman!');
    }
}

let persons: Person[] = [];
persons.push(new Man(24));
persons.push(new Woman(27));
persons.push(new Man(42));
persons.push(new Woman(35));

// 直接调用hello方法,自动适配子类实现
for(let person of persons){
    person.hello();
}

这样运行后就能得到你想要的输出,而且代码更易维护,后续新增子类只需要实现hello方法即可,不需要修改循环逻辑。

内容的提问来源于stack exchange,提问作者dryant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:10:28