การขยายอินเตอร์เฟซใน OOP ใน TypeScript
อินเตอร์เฟซใน TypeScript สามารถสืบทอด
หากันได้ การมีปฏิสัมพันธ์เช่นนี้
เรียกว่า การขยาย อินเตอร์เฟซ
ลองดูตัวอย่าง สมมติว่าเรามี
อินเตอร์เฟซ ISize:
interface ISize {
height: number;
width: number;
}
มาสร้างอินเตอร์เฟซ IStyle ซึ่ง
จะขยาย ISize:
interface IStyle extends ISize {
color: string;
}
ทีนี้มาสร้างคลาส Figure
ที่ใช้อินเตอร์เฟซ IStyle คลาส
ของเราจะต้องมีทั้งคุณสมบัติ
ของอินเตอร์เฟซตัวเองและของอินเตอร์เฟซหลัก
มาสร้างกัน:
class Figure implements IStyle {
height: number;
width: number;
color: string;
constructor(height: number, width: number, color: string) {
this.height = height;
this.width = width;
this.color = color;
}
}
ทดลองใช้งาน:
let fig = new Figure(130, 200, 'green');
console.log(fig);
สร้างอินเตอร์เฟซ IProgrammer พร้อม
คุณสมบัติ salary และ language
ให้อินเตอร์เฟซนี้สืบทอด IUser
ซึ่งมีคุณสมบัติ name, birthday
สร้างคลาส Employee ซึ่ง
ใช้อินเตอร์เฟซ IProgrammer