Skip to content

TypeScript vs JavaScript

คุณสมบัติJavaScriptTypeScript
Type SystemDynamic (weak) typingStatic (strong) typing
Type CheckingRuntimeCompile-time
Error Detectionตรวจพบเมื่อรันโค้ดตรวจพบก่อนรันโค้ด
IDE Supportมีข้อจำกัดIntellisense, code completion, refactoring ที่ดีกว่า
Documentationต้องใช้ JSDocType 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
}