今日なんとなく、こんなん書けたら素敵だなと思ってやったらコンパイル通って驚いたので。
普通のInterfaceの使い方。
便利。感動。
interface NameInterface { firstName: string; secondName: string; fullName: string; }; class Name implements NameInterface { constructor(firstName:string, secondName:string) { this.firstName = firstName; this.secondName = secondName; } firstName: string; secondName: string; get fullName() { return `${this.firstName} ${this.secondName}`; }; }; const yoshio = new Name('たけし', 'アンダーソン'); // たけし アンダーソン console.log(yoshio.fullName);
続いて、型としてInterfaceを使ったとき。
宇宙を感じる。
interface NameInterface { firstName: string; secondName: string; fullName: string; }; const masahiro: NameInterface = { firstName: 'まさひろ', secondName: 'アンダーソン', get fullName() { return `${this.firstName} ${this.secondName}`; } } console.log(masahiro.fullName); // まさひろ アンダーソン
え、初期化時に算出プロパティ定義して渡せるの!?
vuexのstateでcomputed的なことをしたい場合に使えそう。