DRYな備忘録

Don't Repeat Yourself.

memo: TypeScriptの継承と型

memo

module Sample {
    export class MyBase1 {
        constructor(public name: string, public age: number){}
        greet(): MyBase1 {
            return this;
        }//これを宣言しておかないと型通らない #0
        ask(){}//これを宣言しておかないとメソッドが無いと言われる #1
    }

    export class Person extends MyBase1 {
        constructor(name: string, age?: number, public birthday?: string) {
            super(name, age);
        }
        greet(): Person {
            console.log("Hi, my name is " + this.name);
            return this;
        }
        ask(){
            console.log("What's up?");
        }
    }
    export class Dog extends MyBase1 {
        constructor(name: string, age?: number, public race?: string) {
            super(name, age);
        }
        greet(): Dog {
            console.log("Bow wow!!!");
            return this;
        }
        ask(){
            console.log("Bowwwwwoooooooooo!!!!");
        }
    }
}
module Proxy {
    export class Master {
        public static request(name: string) {
            return Master.getServant(name).greet().ask();// ここ#1
        }
        private static getServant(name: string): Sample.MyBase1 {// ここ#0
            if (name == 'tanaka') return new Sample.Person('Tanaka');
            if (name == 'pochi') return new Sample.Dog('pochi');
            throw "誰ですかそれは";
        }
    }
}

(function(){
    Proxy.Master.request('tanaka');
    Proxy.Master.request('pochi');
    Proxy.Master.request('tom');
})();

output

[16:43:55] ➜ tsc sample.ts; node sample.js
Hi, my name is Tanaka
What's up?
Bow wow!!!
Bowwwwwoooooooooo!!!!

/Users/otiai10/sample.js:69
            throw "誰ですかそれは";
            ^
誰ですかそれは