Search code examples
typescriptabstract-classabstract

Declaring abstract method in TypeScript


I am trying to figure out how to correctly define abstract methods in TypeScript:

Using the original inheritance example:

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

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

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.


Solution

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

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

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