typescript - การสร้างสมาชิกย่อยของอาร์เรย์แบบมีชนิดของคลาส
ฉันอยากจะสร้างอาร์เรย์ที่มีประเภท (typed array) เพื่อเพิ่มเมธอดให้กับมัน ตัวอย่างเช่นในตัวอย่างด้านล่าง ฉันสร้าง TenantArray โดยการขยายจาก Array ดูเหมือนว่าฉันสามารถ push วัตถุเข้าไปในนั้นได้ แต่ถ้าฉันพยายามเรียกใช้ฟังก์ชันบน TenantArray ฉันจะได้รับข้อผิดพลาดบอกว่ามันไม่ใช่ฟังก์ชัน ถ้าฉันลอง log ค่าของฟังก์ชันเพียงอย่างเดียว ฉันจะได้ค่า undefined ใครสามารถให้ข้อมูลเชิงลึกเกี่ยวกับสิ่งที่ฉันพลาดได้ไหม นี่เป็นวิธีที่โง่หรือเปล่า หรือว่าฉันควรสร้างคลาสประชากร (population class) ที่มีอาร์เรย์ tenants และฟังก์ชันที่เรียกใช้อาร์เรย์นั้นแทน?
class Manor {
name: string;
tenants: Tenants;
constructor() {
this.name = '';
this.tenants = new Tenants();
}
}
interface ITenant {
acres: number
}
class Tenants extends Array<ITenant> {
totalAcres(): number {
let total = 0;
for (const tenant of this) {
total += tenant.acres;
}
return total;
}
}
const myManor = new Manor();
console.log(myManor.tenants.totalAcres());