Skip to content

Nhap mon He thong Kieu

Loi noi dau

Tai sao "1" + 1 trong JavaScript cho "11", nhung trong Python lai bao loi? Phia sau la he thong kieu dang hoat dong. He thong kieu la "quy tac giao thong" cua ngon ngu -- no quyet dinh du lieu co the su dung nhu the nao, co the tinh toan voi ai, va khi nao kiem tra tinh hop phap. Hieu he thong kieu giup ban hieu "su khac biet ve tinh cach" giua cac ngon ngu.

Bai viet nay se giup ban hoc gi?

Sau khi hoc xong chuong nay, ban se co duoc:

  • Kha nang phan loai: lam chu phuong phap phan loai bon tu (tinh/dong, manh/yeu)
  • Chan doan van de: khi thay TypeError, dinh vi nhanh la khong phu hop kieu hay chuyen doi an
  • Lua chon ngon ngu: hieu tai sao TypeScript phu hop du an lon, Python phu hop nguyen mau nhanh
  • Sue dien kieu: hieu ngon ngu hien dai can bang don gian va an toan nhu the nao
  • Y thuc thuc hanh: lam chu thoi quen code an toan kieu
ChuongNoi dungKhai niem cot loi
Chuong 1He thong kieu la giBan chat cua kieu, tai sao can kieu
Chuong 2Tinh vs DongThoi diem kiem tra, ho tro IDE, an toan
Chuong 3Manh vs YeuChuyen doi an, an toan kieu
Chuong 4Sue dien kieuSue dien tu dong, tot ca hai
Chuong 5GenericTham so kieu, rang buoc kieu, tai su dung
Chuong 6An toan kieu thuc hanhBay thuong gap, chien luoc phong thu
Chuong 7Tu doan kieuPhan loai bon tu, lua chon ngon ngu

0. Toan canh: Kieu la "CMND" cua du lieu

Trong doi thuc, ban khong nhay mot cuon sach vao coc ca phe -- vi chung la nhung "kieu" khac nhau. The gioi lap trinh cung vay: so, chuoi, boolean, mang... moi du lieu co "danh tinh" rieng, quyet dinh no co the tham gia phep toan nao.

He thong kieu la bo quy tac ma ngon ngu su dung de quan ly cac "danh tinh" nay. No tra loi hai cau hoi cot loi:

Hai cau hoi cot loi cua he thong kieu

  • Khi nao kiem tra? Khi viet code (tinh) hay khi chay (dong)?
  • Nghiem ngat bao nhieu? Cam hon hop (manh) hay tu dong chuyen doi (yeu)?

1. He thong kieu la gi: Quy tac giao thong cua du lieu

Type System ExplorerStatic vs dynamic · strong vs weak typing · type inference
StrongWeakStaticDynamic
Strong + static
JavaRustHaskell
Weak + static
CC++
Strong + dynamic
PythonRuby
Weak + dynamic
JavaScriptPHP
Strong + static
Strict compile-time checking with no implicit conversion. Very safe and IDE-friendly, but more verbose.
Compile-time checksNo implicit conversionAutocomplete-friendlySafe refactoring
Core idea:Type systems choose along two dimensions: when checks happen (static/dynamic) and whether implicit conversion is allowed (strong/weak). There is no best combination, only the best fit for a scenario.

Ban chat he thong kieu la mot bo quy tac rang buoc, bao trinh bien dich hoac thong dich:

  • Bien nay co the luu gia tri gi?
  • Hai gia tri nay co the cong duoc khong?
  • Tham so cua ham nay nen la gi?

The gioi khong co he thong kieu nhu con duong khong co quy tac giao thong -- bat ky du lieu nao cung co the phep toan voi bat ky du lieu nao, ket qua hoan toan khong the doan truoc.

Chuc nang cua he thong kieuGiai thichVi du
Ngan phep toan khong hop leChan thao tac vo nghiaKhong the chia mot chuoi
Cung cap thong tin tai lieuKieu la tai lieu tot nhatfunction add(a: number, b: number) ro rang
Ho tro cong cu IDETu dong hoan thanh, cau truc laiuser. tu hien tat ca thuoc tinh
Toi uu hieu suatTrinh bien dich tao code nhanh hon khi biet kieuBiet la so nguyen dung lenh so nguyen

2. Tinh vs Dong: Khi nao kiem tra?

Day la chieu phan loai quan trong nhat -- thoi diem kiem tra.

🔍 Static vs Dynamic Typing: Live Comparison

Choose a code sample and compare how the two type systems behave

Static typing (TypeScript)⏱ Checked at compile time
let name: string = "Alice"
name = 42  // ❌ compile error
❌ Type "number" is not assignable to type "string"
VS
Dynamic typing (JavaScript)⏱ Checked at runtime
let name = "Alice"
name = 42  // ✅ OK
✅ Runs normally; name becomes 42
💡 Static typing catches the error while you write code. Dynamic typing waits until runtime.

Khac biet cot loi

  • Tinh: kieu bien duoc xac dinh khi bien dich, viet xong code truoc khi chay da co the tim loi kieu. Dai dien: Java, TypeScript, Rust, Go.
  • Dong: kieu bien duoc xac dinh khi chay, cung mot bien co the luu so roi luu chuoi. Dai dien: Python, JavaScript, Ruby, PHP.

3. Manh vs Yeu: Co cho phep "chuyen doi an" khong?

⚡ Strong vs Weak Typing: Implicit Conversion Lab

Choose an expression and see how different languages handle it

JavaScriptWeak
"1" + 1
→ "11" (string concatenation)
PythonStrong
"1" + 1
→ TypeError: can only concatenate str to str
JavaWeak
"1" + 1
→ "11" (string concatenation)
RustStrong
"1" + 1
→ compile error: type mismatch
📌 Strongly typed languages refuse to guess your intent. Weakly typed languages may helpfully convert, but the result may be wrong.

Khac biet cot loi

  • Manh: khong cho phep chuyen doi an, kieu khong khop thi bao loi. Ban phai noi ro "toi muon chuyen chuoi nay thanh so".
  • Yeu: cho phep chuyen doi an, ngon ngu se "tot bu" chuyen ho ban. Nhung "long tot" nay thuong mang den bug bat ngo.

4. Sue dien kieu: Tot ca hai

🧠 Type Inference: How the Compiler Guesses Types

Click a code line to see how the compiler infers the type step by step

1let x = 42 → number
2let names = ["Alice", "Bob"]
3let result = x > 10 ? "big" : "small"
4const add = (a: number, b: number) => a + b
5let mixed = [1, "two", true]
Inference process
1The right side is literal 42
242 is an integer-like number
3Infer x as number
Type Inference Capability by Language
Rust
Almost fully inferred
TypeScript
Most types inferred
Kotlin
Strong local inference
Go
Mainly := short declarations
Java
var keyword (Java 10+)
C
Almost none

Gia tri cua sue dien kieu

Viet don gian nhu ngon ngu dong, trinh bien dich kiem tra nghiem nhu ngon ngu tinh. Day la huong chinh cua ngon ngu hien dai.


5. Generic: Viet mot lan, dung cho moi kieu

🧩 Generics: Write Once, Use with Any Type

Choose a scenario and see how generics keep code flexible and safe

❌ Without generics
// Need one function per type
function getFirstNumber(arr: number[]): number {
  return arr[0]
}
function getFirstString(arr: string[]): string {
  return arr[0]
}
// boolean, object... it never ends
You repeat the same code for every type.
✅ With generics
// One generic function handles all types
function getFirst<T>(arr: T[]): T {
  return arr[0]
}

getFirst<number>([1, 2, 3])   // → number
getFirst<string>(["a", "b"])  // → string
T is a type parameter and is replaced by the actual type at call time.
Type flow
T = numberarr: number[]return: number

Gia tri cot loi cua Generic

  • Tai su dung code: mot ham/lop cho moi kieu
  • An toan kieu: khac voi any tu bo kiem tra, generic giu thong tin kieu
  • Rang buoc kieu: dung extends gioi han pham vi, linh hoat va an toan

6. An toan kieu thuc hanh: Bay thuong gap va phong thu

🛡️ Type Safety in Practice: Traps and Defenses

Choose a common trap and learn how the type system protects code

⚠️ Dangerous code
function getLength(str) {
  return str.length  // what if str is null?
}
getLength(null)  // 💥 runtime crash
💥 TypeError: Cannot read properties of null
✅ Safe code
function getLength(str: string | null): number {
  if (str === null) return 0
  return str.length  // ✅ compiler knows str is not null here
}
✅ The compiler forces you to handle null
🔑 Defense strategy
  • Enable strictNullChecks
  • Use string | null to mark nullable values explicitly
  • Use optional chaining ?. for safe access

Bon quy tac vang cua an toan kieu

  1. Bat che do nghiem ngat: strict: true trong TypeScript, mypy --strict trong Python
  2. Tranh any: dung unknown thay any, buoc kiem tra truoc khi su dung
  3. Xu ly null ro rang: dung optional chaining ?. va nullish coalescing ??
  4. Dinh nghia interface cho API: du lieu ben ngoai khong bao gio tin duoc, dung interface + kiem tra luc chay

7. Tu doan kieu: "Chan dung" ngon ngu

Programming Language Type ModelsHow type systems differ across languages
When types are checked
Static typing
Java, C++, Rust, Go
Dynamic typing
Python, JavaScript, Ruby
Type strength
Strong typing
Python, Java, Rust
Weak typing
JavaScript, C, PHP
Type System Classification Matrix
Static + strong
Java, C++, Rust, Go
Compile-time checks with type safety
Static + weak
C
Compile-time checks with flexible conversion
Dynamic + strong
Python, Ruby
Runtime checks with type safety
Dynamic + weak
JavaScript, PHP
Runtime checks with flexible typing
Type Inference
Modern languages can infer variable types automatically without explicit declarations.
TypeScript
let x = 5; // inferred as number
let name = "Alice"; // string
Rust
let x = 5; // inferred as i32
let name = "Alice"; // &str
Tu doanDac diemNgon ngu dai dienTruong hop su dung
Tinh + ManhAn toan nhat, kiem tra nghiem khi bien dichRust, Java, HaskellHe thong lon, an toan then chot
Tinh + YeuKiem tra khi bien dich nhung cho chuyen doi anC, C++Lap trinh he thong, hieu suat
Dong + ManhKiem tra luc chay, khong cho chuyen doi anPython, RubyScript, nguyen mau nhanh
Dong + YeuLinh hoat nhat, cung de loi nhatJavaScript, PHPFrontend web, script nho

Tom tat

He thong kieu la goc nhin cot loi de hieu su khac biet giua cac ngon ngu. No khong phai ly thuyet kho han, ma anh huong truc tiep trai nghiem viet code va chat luong code.

Cac diem cot loi:

  1. Kieu la danh tinh: moi du lieu co kieu, kieu quyet dinh co the tham gia gi
  2. Tinh vs Dong: khi nao kiem tra kieu -- bien dich hay chay
  3. Manh vs Yeu: co cho phep chuyen doi an khong
  4. Sue dien kieu: ngon ngu hien dai cho ban don gian dong va an toan tinh
  5. Generic: tai su dung code voi tham so kieu
  6. An toan thuc hanh: null, any, chuyen doi an la bay thuong gap nhat
  7. Bon tu: khong co he thong kieu tot nhat, chi co phu hop nhat

Doc them