DRYな備忘録

Don't Repeat Yourself.

TypeScriptのinterface制限のextendsと、ついでにダックタイピングのメモ

問題

  • interfaceってextendsできるんだっけ?
  • メソッドとプロパティさえ満たしてれば型制約突破できるんだっけ?(ダックタイピング)

メモ

interface Speaker {
    Speak(s: string): void;
}
interface Person extends Speaker {
    name: string;
    Greet(): void;
}

class Duck {
    constructor(public name: string) {}
    public Speak(s: string) {
        console.log(s);
    }
    public Greet() {
        this.Speak("人間じゃないけど、ぼく、" + this.name);
    }
}

var d: Person = new Duck("ドナルド");

d.Greet();

無事ビルドできた。ビルド後のjs

var Duck = (function () {
    function Duck(name) {
        this.name = name;
    }
    Duck.prototype.Speak = function (s) {
        console.log(s);
    };
    Duck.prototype.Greet = function () {
        this.Speak("人間じゃないけど、ぼく、" + this.name);
    };
    return Duck;
})();

var d = new Duck("ドナルド");

d.Greet();