Part 06 · TypeScript · 6.1.08

Structural typing, inference, unions và narrowing

TypeScript kiểm tra source rồi erase types; JSON/network/localStorage vẫn là unknown cho đến khi runtime validation chứng minh shape.

Boundary rule: type annotation không parse hoặc validate input. Chuyển unknown thành domain type qua schema/guard có evidence, không dùng as để che failure.

1. Structural model và inference

Compatibility dựa trên members, không nominal identity. Excess-property checks mạnh hơn với fresh literals nhưng không biến TypeScript thành exact object types. Inference giúp giảm annotation nhưng cần kiểm tra widening, contextual typing và public API stability.

Mutable variance và callback parameter compatibility có soundness trade-off; strict mode làm các khoảng mơ hồ lộ sớm hơn.

2. Top/bottom types

TypeÝ nghĩaPolicy
unknownGiá trị chưa biết, phải narrow trước useDefault cho external input
anyTắt checker và lan truyền unsafetyLocalize, document reason, lint
neverKhông thể xảy ra/exhaustivenessDùng ở assertNever hoặc impossible branch
voidGiá trị return không hữu íchKhông nhầm với async cancellation

3. Unions và control-flow narrowing

Discriminated union model state machine; typeof, in, instanceof, equality checks và custom predicates narrow theo control flow. Exhaustive switch với never bắt missing case khi union phát triển.

type Result = {kind: "ok"; value: string} | {kind: "error"; message: string};
function render(r: Result) {
  switch (r.kind) {
    case "ok": return r.value;
    case "error": return r.message;
    default: return assertNever(r);
  }
}

4. Nullability và runtime validation

strictNullChecks tách null/undefined; optional property khác property union undefined khi bật exactOptionalPropertyTypes. Non-null assertion chỉ xóa checker warning, không tạo runtime proof. Validate external data bằng schema/guard rồi map sang domain object.

Interview answer: “TypeScript improves developer feedback, not runtime trust. I keep unknown at boundaries, narrow with validated predicates, and localize any/assertions with an explicit invariant.”
Tài liệu: TypeScript Everyday Types · TypeScript Narrowing · strictNullChecks