</>
⌕
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

FlagTác dụng
strictNullChecksnull/undefined không gán được cho type khác; bắt buộc kiểm tra
noImplicitAnybáo lỗi khi suy luận ra any ngầm (thiếu type tham số)
strictFunctionTypestham số hàm kiểm tra contravariant (không áp cho method)
strictBindCallApplykiểm tra đối số của bind/call/apply
strictPropertyInitializationproperty class phải được khởi tạo trong constructor
noImplicitThisthis không được ngầm là any
useUnknownInCatchVariablesbiến trong catch là unknown thay vì any
alwaysStrictphá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ểu T | undefined.
  • exactOptionalPropertyTypes: phân biệt “không có key” và “có key giá trị undefined”.
  • noImplicitOverride: bắt buộc override khi 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).
🃏 Ôn bằng flashcard