Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript how to force inherited class to implement a method

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?

like image 248
Mustafa Dwekat Avatar asked Mar 20 '16 12:03

Mustafa Dwekat


2 Answers

You can declare your Animal class with the abstract keyword and same for the method you want to force in the child class.

abstract class Animal {
    abstract speak(): string;
}

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

You can find more information about abstract classes and methods in the TypeScript Handbook.

like image 181
Fidan Hakaj Avatar answered Oct 13 '22 08:10

Fidan Hakaj


As of TypeScript 1.6 you can now declare classes and method abstract. For example:-

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

Unfortunately the documentation hasn't caught up yet https://github.com/Microsoft/TypeScript/blob/v2.6.0/doc/spec.md#8-classes

like image 28
Suleman C Avatar answered Oct 13 '22 09:10

Suleman C