TypeScript cho JavaScript developer: những gì thực sự cần biết để bắt đầu

TypeScript không phải ngôn ngữ mới — nó là JavaScript với type annotations thêm vào. Mọi JS code hợp lệ đều là TS code hợp lệ. TypeScript compiler (tsc) chuyển TS → JS trước khi chạy, và type errors chỉ xảy ra ở compile time, không ảnh hưởng runtime. Bài này tập trung vào những gì thực sự cần biết để bắt đầu dùng TypeScript hiệu quả — không phải toàn bộ type system.

Type inference — TS đủ thông minh để tự suy ra

Một trong những điều quan trọng nhất: bạn không cần annotate mọi thứ.

// TypeScript tự suy ra type — không cần viết `: string`
const name = "Alice"           // type: string
const age = 25                 // type: number
const isActive = true          // type: boolean

const numbers = [1, 2, 3]     // type: number[]
const mixed = [1, "hello"]    // type: (string | number)[]

// Function return type cũng được inference
function add(a: number, b: number) {
  return a + b   // TypeScript biết return type là number
}

Chỉ cần explicit type annotation khi: function parameters, API response types, hoặc khi TS inference ra type sai.

Primitive types và khai báo cơ bản

// Primitive types
let username: string = "Alice"
let score: number = 100
let isLoggedIn: boolean = false
let nothing: null = null
let notDefined: undefined = undefined

// Array
let tags: string[] = ["react", "typescript"]
let scores: Array<number> = [90, 85, 92]  // syntax khác, cùng kết quả

// Object inline
let user: { name: string; age: number; email?: string } = {
  name: "Alice",
  age: 25
  // email là optional (dấu ?)
}

Interface vs Type alias — cái nào dùng?

// Interface — có thể extend và declaration merging
interface User {
  id: number
  name: string
  email: string
}

interface AdminUser extends User {
  role: "admin" | "superadmin"
  permissions: string[]
}

// Type alias — linh hoạt hơn với union và intersection
type Status = "active" | "inactive" | "pending"
type ID = string | number  // union

type UserWithStatus = User & { status: Status }  // intersection

Thực tế: Cả hai đều OK. Convention phổ biến: dùng interface cho object shapes (đặc biệt khi cần extend), dùng type cho union types, primitive aliases, và mapped types. Quan trọng nhất: nhất quán trong project.

Union types — cực kỳ hữu ích

type Direction = "north" | "south" | "east" | "west"
type StringOrNumber = string | number

function formatId(id: string | number): string {
  if (typeof id === "number") {
    return id.toString().padStart(5, "0")  // "00042"
  }
  return id.toUpperCase()
}

// TypeScript biết trong mỗi branch, type là gì — type narrowing
formatId(42)        // "00042"
formatId("abc123")  // "ABC123"

Generics cơ bản

// Không có generics — phải viết riêng cho từng type
function firstNumber(arr: number[]): number | undefined {
  return arr[0]
}

// Với generics — dùng được với mọi type
function first<T>(arr: T[]): T | undefined {
  return arr[0]
}

first([1, 2, 3])           // TypeScript biết return type là number | undefined
first(["a", "b", "c"])     // return type là string | undefined
first([{ id: 1 }, { id: 2 }])  // return type là { id: number } | undefined

// Generic với constraint — T phải có property id
function findById<T extends { id: number }>(arr: T[], id: number): T | undefined {
  return arr.find(item => item.id === id)
}

Strict mode — bật ngay từ đầu

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "strict": true,          // bật tất cả strict checks
    "outDir": "./dist",
    "rootDir": "./src",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

"strict": true bật nhiều checks, quan trọng nhất là strictNullChecks — phân biệt null/undefined với các type khác. Sẽ gây thêm errors ban đầu nhưng bắt được nhiều bugs tiềm ẩn.

Optional chaining và nullish coalescing

interface Profile {
  user?: {
    address?: {
      city?: string
    }
  }
}

const profile: Profile = {}

// Không có optional chaining — dễ runtime error
// const city = profile.user.address.city  // TypeError!

// Với optional chaining — safe
const city = profile.user?.address?.city  // undefined, không throw

// Nullish coalescing — fallback khi null hoặc undefined
const displayCity = profile.user?.address?.city ?? "Chưa cập nhật"

Migrate dần từ JS sang TS

  1. Cài TypeScript: npm install -D typescript @types/node
  2. Tạo tsconfig.json với "allowJs": true để JS và TS cùng tồn tại
  3. Đổi từng file .js thành .ts dần dần
  4. Dùng // @ts-ignore hoặc any tạm thời cho những chỗ khó
  5. Bật strict: true sau khi đã migrate xong phần lớn codebase

@types packages cho thư viện JS thuần

# Thư viện JS thuần không có type definitions built-in
npm install -D @types/node       # Node.js built-ins
npm install -D @types/express    # Express.js
npm install -D @types/lodash     # Lodash

# Nhiều thư viện modern đã ship type definitions built-in (không cần @types)
# Ví dụ: axios, zod, prisma, drizzle-orm

Lỗi TypeScript phổ biến và cách fix

// Lỗi: Object is possibly undefined
const user = users.find(u => u.id === id)
// user.name  // Error!

// Fix: check trước
if (user) {
  console.log(user.name)  // OK
}
// Hoặc optional chaining
console.log(user?.name)

// Lỗi: Argument of type 'string' is not assignable to 'Status'
type Status = "active" | "inactive"
const s: Status = "active"  // OK
// const s: Status = "deleted"  // Error — "deleted" không có trong union

// Lỗi: Property 'role' does not exist on type 'User'
// Fix: thêm vào interface, hoặc dùng type assertion nếu biết chắc
const admin = user as AdminUser  // type assertion — TS tin bạn
← Về danh sách Blog