オブジェクトを拡張する時のオブジェクトリテラルとクラスの比較オブジェクトの作成A:オブジェクトリテラルtype TA = { name: string; getLength: () => number; }; const A = (val: string): TA => { const name = val; const getLength = () => { return name.length; }; return { name, getLength, }; }; B:クラスclass B { name: string = ""; constructor(val: string) { this.name = val; } getLength() { return this.name.length; } } AとBの使用const _a = A("AAA"); console.log(_a.getLength()); const _b = new B("BBB"); console.log(_b.getLength()); ほぼ同じ機能 オブジェクトの拡張Aの拡張const _a2: TA & { x: number } = { ..._a, x: 1 }; console.log(_a2.getLength(), _a2.x); Bの拡張class BExtended extends B { x: number; constructor(val: string, x: number) { super(val); this.x = x; } } const _b2 = new BExtended("CCC", 1); console.log(_b2.getLength(), _b2.x); Bはクラスなので記述が冗長になる |
|