Mid #tsconfig#strict#compiler-options
`strict` trong tsconfig bật những flag nào? Nên bật thêm flag nào?
⚡ Trả lời nhanh
`strict: true` bật nhóm kiểm tra chặt: `strictNullChecks`, `noImplicitAny`, `strictFunctionTypes`, `strictBindCallApply`, `strictPropertyInitialization`, `noImplicitThis`, `useUnknownInCatchVariables`, `alwaysStrict`. Nên bật thêm `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noImplicitOverride` vì không nằm trong `strict`.
Các flag trong strict
| Flag | Tác dụng |
|---|---|
strictNullChecks | null/undefined không gán được cho type khác; bắt buộc kiểm tra |
noImplicitAny | báo lỗi khi suy luận ra any ngầm (thiếu type tham số) |
strictFunctionTypes | tham số hàm kiểm tra contravariant (không áp cho method) |
strictBindCallApply | kiểm tra đối số của bind/call/apply |
strictPropertyInitialization | property class phải được khởi tạo trong constructor |
noImplicitThis | this không được ngầm là any |
useUnknownInCatchVariables | biến trong catch là unknown thay vì any |
alwaysStrict | phát ra "use strict" cho mọi file |
strictBuiltinIteratorReturn | (TS 5.6) iterator dựng sẵn trả undefined thay vì any khi done |
Flag hay nên thêm (ngoài strict)
noUncheckedIndexedAccess:arr[i]vàobj[key]có kiểuT | undefined.exactOptionalPropertyTypes: phân biệt “không có key” và “có key giá trị undefined”.noImplicitOverride: bắt buộcoverridekhi ghi đè method của class cha.noFallthroughCasesInSwitch,noImplicitReturns: bắt lỗi luồng điều khiển.verbatimModuleSyntax/isolatedModules: an toàn khi build bằng tool chỉ xóa type (esbuild, swc).