
หลายคนที่ใช้ TypeScript มาคงจะเจอปัญหาว่าเจ้า Type กับ Interface มันต่างกันยังไง หากได้ไป opensource ต่างๆ ก็จะพบว่า บางอันก็ใช้ Type เป็นหลัก บางที่ก็ใช้ Interface เป็นหลัก จริงๆ แล้วเราควรจะใช้อันไหนกันแน่ มาหาคำตอบกัน…
ก่อนอื่นมาดูตัวอย่างการประกาศ properties กันก่อน
Type
type BirdType = {
wings: 2;
};Interface
interface BirdInterface {
wings: 2;
}เริ่มประกาศตัวแปรพื้นฐานโดยใช้ Type และ Interface ที่สร้างมา
const bird1: BirdType = { wings: 2 };
const bird2: BirdInterface = { wings: 2 };
const bird3: BirdInterface = bird1;จากนั้นเราจะทำการเพิ่ม properties โดยการประกาศ Type และ Interface จากของเดิมที่เราได้สร้างไว้
type Owl = { nocturnal: true } & BirdType;
type Robin = { nocturnal: false } & BirdInterface;
interface Peacock extends BirdType {
colourful: true;
flies: false;
}
interface Chicken extends BirdInterface {
colourful: false;
flies: false;
}จะเห็นว่าทั้ง Type และ Interface สามารถนำเพิ่ม properties ได้ แค่ syntax ต่างกันเท่านั้น และยังสามารถใช้สลับกันได้ด้วย!
สิ่งที่แตกต่างกัน
1. ข้อความ error
หากเราทำการประกาศตัวแปร และมี properties บางตัวหายไปนั้น
let owl: Owl = { wings: 2, nocturnal: true };
let chicken: Chicken = { wings: 2, colourful: false, flies: false };
owl = chicken;
chicken = owl;ข้อความ error จาก Type
Type 'Chicken' is not assignable to type 'Owl'.
Property 'nocturnal' is missing in type 'Chicken' but required in type '{ nocturnal: true; }'.
ข้อความ error จาก Interface
Type 'Owl' is missing the following properties from type 'Chicken': colourful, flies
จะเห็นว่าถ้าเราประกาศตัวแปรเป็น Interface ข้อความ error จะสั้นกว่าและค่อนข้างเข้าใจง่ายกว่าด้วย
2. เราสามารถใช้ alias ในการเพิ่ม properties ให้ Interface ได้ แต่ใช้กับ Type ไม่ได้
เพิ่ม property ให้ Kitten
interface Kitten {
purrs: boolean;
}
interface Kitten {
colour: string;
}
let cat: Kitten = { purrs: true, colour: 'yellow' }จะเห็นว่าในการประกาศ interface ชื่อเหมือนกัน มันจะทำการ extend หรือเพิ่ม property ให้ Kitten โดยอัตโนมัติและไม่เกิด error
แต่ถ้าเราทำแบบเดียวกันกับ Type ล่ะ
type Puppy = {
color: string;
};
type Puppy = {
toys: number;
};Duplicate identifier 'Puppy'
มันจะพ่น error ออกมาเลยว่าตัวแปรซ้ำ ไม่สามารถประกาศอีกครั้งได้
สรุป
เราสามารถใช้ทั้ง Type และ Interface สลับกันได้ ซึ่งตัว Interface เองสามารถทำเหมือนกับ Type ได้เกือบหมด สิ่งสำคัญคือเราควรมีการตกลง code standard กันในทีมก่อนว่าจะเอาแบบไหนเป็น default ไม่งั้นในโค้ดของเราจะมี 2 ตัวนี้ปนกันมั่วไปหมด
ซึ่งก็จะมี edge case ต่างๆ อีกที่ไม่สามารถใช้แทนกันได้บางกรณี สามารถไปดูต่อได้ตามลิ้งด้านล่างได้เลย
https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript/52682220#52682220


