In TypeScript how to force inherited class to implement a method

Viewed 14323

I need to force the class to implement some method for example onCreate(), as in other languages like php we can see something like:

<?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)

    }

}

?>

Note that in my example if I didn't implement onWalk() the code will not work and you will get an error but when I do the same in TypeScript as following:

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

    }

}

No error will show whether I did or didn't implement the on walk method but the it will give an error if I didn't implement onWalk() in the Animal class, I need to have same as php in TypeScript?

2 Answers
Related