在 TypeScript 中声明抽象方法 [英] Declaring abstract method in TypeScript

查看:35
本文介绍了在 TypeScript 中声明抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to figure out how to correctly define abstract methods in 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 方法,因此它被输入并且可能被覆盖.

I would like to know how to correctly define method makeSound, so it is typed and possible to overried.

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

Also, I am not sure how to define correctly protected methods - it seems to be a keyword, but has no effect and the code won't compile.

推荐答案

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

The name property is marked as protected. This was added in TypeScript 1.3 and is now firmly established.

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

The makeSound method is marked as abstract, as is the class. You cannot directly instantiate an Animal now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.

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 出现在您的项目中,您就不需要再这样做了:

The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:

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);
    }
}

这篇关于在 TypeScript 中声明抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆