Năm 2012, Microsoft phát hành TypeScript và nhiều người cười nhạo: "Tại sao thêm type vào JavaScript?". Năm 2024, hơn 80% developer JavaScript dùng TypeScript trong các dự án lớn. Điều gì đã thay đổi?
JavaScript Và Vấn Đề Của Nó
// JavaScript — không có gì ngăn bạn làm điều này
function tinh_tong(a, b) {
return a + b;
}
tinh_tong(1, 2) // 3 ✓
tinh_tong("1", "2") // "12" — string concatenation!
tinh_tong(null, {}) // "null[object Object]" ???
TypeScript bắt những lỗi này lúc viết code, không phải lúc chạy production.
TypeScript Cơ Bản
// TypeScript
function tinh_tong(a: number, b: number): number {
return a + b;
}
tinh_tong(1, 2) // 3 ✓
tinh_tong("1", "2") // Lỗi compile! ✗
tinh_tong(null, {}) // Lỗi compile! ✗
Types Cơ Bản
// Primitive types
let ten: string = "Duc";
let tuoi: number = 25;
let active: boolean = true;
// Arrays
let tags: string[] = ["python", "django"];
let diem: Array = [9, 8, 10];
// Tuple
let toa_do: [number, number] = [10.5, 106.7];
// Any — tránh dùng
let something: any = "anything goes";
Interface Và Type
interface Post {
id: number;
title: string;
content: string;
published?: boolean; // optional
}
// Type alias
type Status = 'draft' | 'published' | 'archived';
interface PostWithStatus extends Post {
status: Status;
}
const bai_viet: PostWithStatus = {
id: 1,
title: "Hello TypeScript",
content: "...",
status: "published"
};
Generics
function first(arr: T[]): T | undefined {
return arr[0];
}
first([1, 2, 3]) // kiểu: number | undefined
first(["a", "b", "c"]) // kiểu: string | undefined
// Generic interface
interface ApiResponse {
data: T;
status: number;
message: string;
}
type PostResponse = ApiResponse;
type ListResponse = ApiResponse;
Utility Types Hữu Ích
interface Post {
id: number;
title: string;
content: string;
published: boolean;
}
// Partial — tất cả fields optional
type PostUpdate = Partial;
// Pick — chọn một số fields
type PostPreview = Pick;
// Omit — loại bỏ fields
type PostCreate = Omit;
// Required — tất cả fields required
type FullPost = Required;
Migrate Từ JavaScript
- Đổi
.jsthành.ts - Thêm
tsconfig.jsonvới"strict": falselúc đầu - Fix lỗi từng file
- Dần bật strict mode
TypeScript không loại bỏ runtime errors — nó chỉ loại bỏ một class lớn của lỗi: type errors. Vẫn cần test, vẫn cần validation. Nhưng refactor code lớn mà không sợ break things — đó là superpower thực sự.
Kết Luận
Bắt đầu với một file TypeScript nhỏ trong project hiện tại. Cảm nhận sự khác biệt khi editor tự gợi ý và cảnh báo. Sau vài tuần, bạn sẽ khó quay lại JavaScript thuần.
Chưa có bình luận. Hãy là người đầu tiên!