Dark mode
TypeScript vs JavaScript
คุณสมบัติ | JavaScript | TypeScript |
---|---|---|
Type System | Dynamic (weak) typing | Static (strong) typing |
Type Checking | Runtime | Compile-time |
Error Detection | ตรวจพบเมื่อรันโค้ด | ตรวจพบก่อนรันโค้ด |
IDE Support | มีข้อจำกัด | Intellisense, code completion, refactoring ที่ดีกว่า |
Documentation | ต้องใช้ JSDoc | Type definitions ทำหน้าที่เป็นเอกสารในตัว |
Maintenance | ยากขึ้นเมื่อโปรเจคใหญ่ขึ้น | ง่ายกว่าเนื่องจากมี type safety |
Refactoring | เสี่ยงต่อการเกิด bug | ปลอดภัยกว่าเพราะ compiler ช่วยตรวจสอบ |
Ecosystem | กว้างขวาง | รองรับ JavaScript ทั้งหมด + type definitions |
Learning Curve | ต่ำกว่า | สูงกว่าเล็กน้อย (ต้องเรียนรู้เรื่อง types) |
Performance | ไม่มีความแตกต่างที่ runtime | ไม่มีความแตกต่างที่ runtime |
ตัวอย่างเปรียบเทียบโค้ด
JavaScript:
javascript
function calculateTotal(items) {
let total = 0;
for (const item of items) {
total += item.price * item.quantity;
}
return total;
}
// อาจเกิดข้อผิดพลาดเมื่อรันโค้ด ถ้า:
// - items ไม่ใช่ array
// - item ไม่มี property price หรือ quantity
// - price หรือ quantity ไม่ใช่ตัวเลข
TypeScript:
typescript
interface Item {
price: number;
quantity: number;
name: string;
}
function calculateTotal(items: Item[]): number {
let total = 0;
for (const item of items) {
total += item.price * item.quantity;
}
return total;
}
// ข้อผิดพลาดจะถูกตรวจพบในขั้นตอนการคอมไพล์:
// - ถ้า items ไม่ใช่ array ของ Item
// - ถ้าพยายามเข้าถึง property ที่ไม่มีใน Item
// - ถ้าพยายามใส่ค่าผิดประเภทให้กับ price หรือ quantity
Benefits of TypeScript
ระบบ Type ที่แข็งแกร่ง
เมื่อกำหนด function ที่รับเฉพาะตัวเลข TypeScript จะแจ้งเตือนทันทีถ้าคุณพยายามใช้สตริงแทน
ts
function add(a: number, b: number) {
return a + b;
}
// Error: Argument of type 'string' is not assignable to parameter of type 'number'
add("1", "2");
ตรวจจับข้อผิดพลาดได้เร็วขึ้น
TypeScript จะแจ้งเตือนทันทีเมื่อพิมพ์ชื่อ property ผิด ไม่ต้องรอให้เกิด undefined error
ts
interface User {
name: string;
email: string;
}
const user: User = { name: "John", email: "[email protected]" };
// Error: Property 'nmae' does not exist on type 'User'. Did you mean 'name'?
console.log(user.nmae);
การพัฒนาที่มีประสิทธิภาพมากขึ้น
IDE แสดงรายการ methods และ properties ที่ใช้ได้ทั้งหมดพร้อมคำอธิบาย ลดการต้องค้นหาเอกสาร
ts
// เมื่อพิมพ์ document. IDE จะแสดงรายการ methods ทั้งหมดที่สามารถใช้ได้
document.querySelector("#app").addEventListener("click", () => {});
เอกสารในตัว
Type definitions ทำหน้าที่เป็นเอกสารในตัว ทำให้เข้าใจโครงสร้างข้อมูลได้ทันทีโดยไม่ต้องอ่านเอกสารเพิ่มเติม
ts
interface User {
id: number;
name: string;
role: "admin" | "user";
}
การบำรุงรักษาที่ดีขึ้น
เมื่อเปลี่ยนแปลงโค้ด TypeScript จะชี้ทุกที่ที่ได้รับผลกระทบและช่วยอัปเดตให้อัตโนมัติ ทำให้การปรับปรุงโค้ดปลอดภัยยิ่งขึ้น
ts
// เมื่อเปลี่ยนชื่อฟังก์ชันหรือเพิ่มพารามิเตอร์
function processUser(user: User, options: Options) {
// implementation
}