"strict": true ใน tsconfig.json เปิดใช้งานตัวตรวจสอบที่เข้มงวดมากขึ้นหลายตัวพร้อมกัน ขอแนะนำให้ใช้สำหรับโปรเจกต์ใหม่ทั้งหมด — มันจะจับจุดบกพร่องที่ TypeScript มีไว้เพื่อป้องกัน
{ "compilerOptions": { "strict": true } }
"strict": true ใน tsconfig.json เปิดใช้งานตัวตรวจสอบที่เข้มงวดมากขึ้นหลายตัวพร้อมกัน ขอแนะนำให้ใช้สำหรับโปรเจกต์ใหม่ทั้งหมด — มันจะจับจุดบกพร่องที่ TypeScript มีไว้เพื่อป้องกัน
{ "compilerOptions": { "strict": true } }
// strictNullChecks — null/undefined are no longer assignable to everything
let name: string = null; // ❌ Error (without strict this compiles, then crashes)
function f(u?: User) { u.name; } // ❌ u is possibly undefined → forces a check
// noImplicitAny — parameters with no inferable type must be annotated
function g(x) {} // ❌ Error: 'x' implicitly has type 'any'
// strictPropertyInitialization — class fields must be initialized
class C { name: string; } // ❌ must init in constructor or mark optional
strictNullChecks เป็นตัวสำคัญ: มันแยก null/undefined ออกจากประเภทอื่น ดังนั้นคอมไพลเลอร์จึงบังคับให้คุณจัดการกับ "อาจจะหายไป" ทุกที่ — ขจัดกลุ่มข้อผิดพลาดรানไทม์อันดับที่ 1 ("cannot read property of undefined")
เปิดใช้งานแฟล็กทีละขั้น (strictNullChecks ก่อน) แก้ไขข้อผิดพลาดไฟล์ต่อไฟล์ แทนที่จะเปิดใช้งานทั้งหมดในเวลาเดียวกันในโปรเจกต์เดิมขนาดใหญ่
หากไม่มี strict mode TypeScript ยังคงอนุญาตรูปแบบที่ไม่ปลอดภัยจำนวนมากที่มันมีไว้เพื่อป้องกัน (implicit any ค่า null ที่ไม่ได้ตรวจสอบ)
Strict mode คือที่ที่ TypeScript ส่งมอบมูลค่าส่วนใหญ่ — ถือว่าเป็นค่าเริ่มต้น และเพียงแต่ผ่อนคลายแฟล็กแต่ละตัวด้วยเหตุผลที่ดี