オブジェクトを拡張する時のオブジェクトリテラルとクラスの比較オブジェクトの作成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はクラスなので記述が冗長になる |
|