ทำไมต้อง TypeScript?

จับข้อผิดพลาดตอน compile time แทน runtime — เขียนโค้ดมั่นใจขึ้น ทีมทำงานร่วมกันได้ง่ายขึ้น และ refactor โดยไม่ต้องกลัว


TypeScript คืออะไร?

// TypeScript = JavaScript + Type System
// Browser รัน JS ได้ตรงๆ → TypeScript ต้อง compile เป็น JS ก่อน

TypeScript (.ts) ──── tsc / Vite ────▶ JavaScript (.js) ────▶ Browser


ปัญหาที่ TypeScript แก้ได้

Runtime Error JavaScript รู้ว่าพังตอนรัน — ผู้ใช้เจอ bug ก่อน

Compile Error TypeScript รู้ว่าพังตอนเขียนโค้ด — จับได้ก่อน deploy

Autocomplete Editor รู้ type → แนะนำ method และ property ได้ถูกต้อง


ตัวอย่าง — JavaScript vs TypeScript

// ✗ JavaScript — รู้ว่าพังตอน runtime
function getFullName(user) {
  return user.firstName + ' ' + user.lastName;
}

getFullName(null); // 💥 TypeError: Cannot read properties of null


// ✓ TypeScript — รู้ว่าพังตอน compile time
interface User {
  firstName: string;
  lastName: string;
}

function getFullName(user: User): string {
  return `${user.firstName} ${user.lastName}`;
}

getFullName(null); // ✗ Error: Argument of type 'null' is not assignable


Types พื้นฐานที่ใช้บ่อย

// Primitive types
let name: string = 'สมชาย';
let age: number = 30;
let isActive: boolean = true;

// Array
let tags: string[] = ['typescript', 'javascript'];
let scores: number[] = [90, 85, 78];

// Union type — รับได้หลาย type
let id: string | number = 42;
id = 'abc-123'; // ✓ ได้ทั้งคู่

// Optional property
interface Config {
  host: string;
  port?: number; // ? = optional ใส่หรือไม่ก็ได้
}


Interface vs Type

// Interface — ใช้กับ Object และ Class
interface Product {
  id: number;
  name: string;
  price: number;
  category?: string;
}

// Type Alias — ยืดหยุ่นกว่า รับ Union และ Intersection ได้
type Status = 'active' | 'inactive' | 'pending';
type ID = string | number;

// ใช้งาน
const product: Product = {
  id: 1,
  name: 'Keyboard',
  price: 1500,
};

let status: Status = 'active';


ตัวอย่าง — Generic Type

// Generic — เขียน function ครั้งเดียว ใช้ได้กับทุก type
function firstItem<T>(arr: T[]): T {
  return arr[0];
}

firstItem([1, 2, 3]);         // return type: number
firstItem(['a', 'b', 'c']);   // return type: string

// API Response wrapper ที่ใช้บ่อย
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

type UserResponse = ApiResponse<User>;
type ProductResponse = ApiResponse<Product[]>;


ตัวอย่าง — TypeScript กับ React

// กำหนด Props type ให้ Component
interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: 'primary' | 'secondary' | 'danger';
  disabled?: boolean;
}

function Button({ label, onClick, variant = 'primary', disabled }: ButtonProps) {
  return (
    <button
      className={`btn btn-${variant}`}
      onClick={onClick}
      disabled={disabled}
    >
      {label}
    </button>
  );
}


เส้นทางเริ่มต้นใช้ TypeScript

1. ติดตั้งและตั้งค่า

npm install typescript — สร้าง tsconfig.json ด้วย tsc --init

2. เริ่มจาก strict: false

ค่อยๆ เพิ่ม type ทีละจุด ไม่ต้องเปลี่ยนทุกอย่างพร้อมกัน

3. ใช้ type inference ให้เป็นประโยชน์

TypeScript เดา type ได้เอง ไม่ต้องระบุทุกตัวแปร

4. เปิด strict: true เมื่อพร้อม

จะช่วยจับ bug ได้มากขึ้น เหมาะกับ project ที่จริงจัง


JavaScript vs TypeScript เปรียบเทียบ

JavaScript ยืดหยุ่นสูง เรียนง่าย แต่ bug ซ่อนอยู่จนกว่าจะรัน

TypeScript เขียนมากขึ้นเล็กน้อย แต่ editor ช่วยได้มาก และ bug น้อยลงมาก