在 TypeScript 中声明抽象方法

新手上路,请多包涵

我试图弄清楚如何在 TypeScript 中正确定义抽象方法:

使用原始继承示例:

 class Animal {
    constructor(public name) { }
    makeSound(input : string) : string;
    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name) { super(name); }
    makeSound(input : string) : string {
        return "sssss"+input;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

我想知道如何正确定义方法 makeSound,所以它是类型化的并且可以被覆盖。

另外,我不确定如何正确定义 protected 方法 - 它似乎是一个关键字,但没有效果并且代码不会编译。

原文由 Vojtěch 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 522
2 个回答

name 属性标记为 protected 。这是在 TypeScript 1.3 中添加的,现在已经牢固确立。

makeSound 方法被标记为 abstract ,类也是如此。您现在不能直接实例化 Animal ,因为它是抽象的。 这是 TypeScript 1.6 的一部分, 现已正式上线。

 abstract class Animal {
    constructor(protected name: string) { }

    abstract makeSound(input : string) : string;

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }

    makeSound(input : string) : string {
        return "sssss"+input;
    }

    move() {
        alert("Slithering...");
        super.move(5);
    }
}

模仿抽象方法的旧方法是在有人使用它时抛出错误。一旦 TypeScript 1.6 进入您的项目,您就不再需要这样做了:

 class Animal {
    constructor(public name) { }
    makeSound(input : string) : string {
        throw new Error('This method is abstract');
    }
    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name) { super(name); }
    makeSound(input : string) : string {
        return "sssss"+input;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

原文由 Fenton 发布,翻译遵循 CC BY-SA 3.0 许可协议

我习惯在基类中抛出异常。

 protected abstractMethod() {
    throw new Error("abstractMethod not implemented");
}

然后你必须在子类中实现。缺点是没有构建错误,而是运行时。优点是你可以从超类调用这个方法,假设它会工作:)

弥尔顿

原文由 Milton 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进