【问题标题】:In TypeScript how to force inherited class to implement a method在 TypeScript 中如何强制继承的类实现方法
【发布时间】:2016-07-06 22:30:52
【问题描述】:

我需要强制类实现一些方法,例如 onCreate(),就像在其他语言中一样,如 php,我们可以看到类似的内容:

<?php

// Declare the interface 'Movement'
interface MovementEvents
{
    public function onWalk($distance);
}

// Declare the abstract class 'Animal'
abstract class Animal implements MovementEvents{

    protected $energy = 100;

    public function useEnergy($amount){
        $energy -= $amount;
    }

}


class Cat extends Animal{

    // If I didn't implement `onWalk()` I will get an error
    public function onWalk($distance){

        $amount = $distance/100;

        $this->useEnergy($amount)

    }

}

?>

请注意,在我的示例中,如果我没有实现 onWalk(),代码将无法运行,您会收到错误消息,但是当我在 TypeScript 中执行相同操作时,如下所示:

// Declare the interface 'Movement'
interface MovementEvents
{
    onWalk: (distance)=>number;
}

// Declare the abstract class 'Animal'
abstract class Animal implements MovementEvents{

    protected energy:number = 100;

    public useEnergy(amount:number):number{

        return this.energy -= amount;

    }

}


class Cat extends Animal{

    // If I didnt implment `onWalk()` I will get an error
    public onWalk(distance:number):number{

        var amount:number = distance/100;

        return this.useEnergy(amount);

    }

}

没有错误会显示我是否实现了 on walk 方法,但如果我没有在 Animal 类中实现 onWalk() 会出错,我需要与 @987654329 相同@在TypeScript?

【问题讨论】:

    标签: class oop typescript


    【解决方案1】:

    您可以使用 abstract 关键字声明您的 Animal 类,并且对于要在子类中强制执行的方法也是如此。

    abstract class Animal {
        abstract speak(): string;
    }
    
    class Cat extends Animal {
        speak() {
            return 'meow!';
        }
    }
    

    您可以在TypeScript Handbook 中找到有关抽象类和方法的更多信息。

    【讨论】:

    • 非常感谢.. 我花了几天时间寻找解决方案。
    • 抽象是游戏的名字!
    • 这对类属性也一样吗?
    【解决方案2】:

    从 TypeScript 1.6 开始,您现在可以声明类和方法 abstract。例如:-

    abstract class Animal {
        abstract makeSound(input : string) : string;
    }
    

    不幸的是,文档还没有跟上 https://github.com/Microsoft/TypeScript/blob/v2.6.0/doc/spec.md#8-classes

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 2014-10-28
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多