Postfix ! บอกให้คอมไพเลอร์ว่า "ฉันรับประกันว่าค่านี้ ไม่ใช่ null หรือ undefined ที่นี่" — ลบ null/undefined ออกจากประเภทของมันโดยไม่มีการตรวจสอบ runtime
ts
() {
.(name!.());
}
Postfix ! บอกให้คอมไพเลอร์ว่า "ฉันรับประกันว่าค่านี้ ไม่ใช่ null หรือ undefined ที่นี่" — ลบ null/undefined ออกจากประเภทของมันโดยไม่มีการตรวจสอบ runtime
() {
.(name!.());
}
เป็นเพียง compile-time assertion — เช่นเดียวกับ as มันไม่ ทำการตรวจสอบ runtime ใดๆ หากคุณผิด มันจะขัดข้อง:
const el = document.getElementById("app")!; // assert non-null
el.innerHTML = "hi"; // 💥 runtime error if #app doesn't actually exist
// 1. You've logically guaranteed it, but the compiler can't see it
if (map.has(key)) map.get(key)!.doThing(); // has() proves get() isn't undefined
// 2. Class fields initialized outside the constructor (DI, lifecycle hooks)
class C { value!: string; } // definite assignment assertion
name?.toUpperCase(); // optional chaining — no crash, yields undefined
const x = name ?? "default"; // provide a fallback
if (name) name.toUpperCase(); // narrow with a real check
แต่ละอันเหล่านี้ จัดการ กรณีที่ขาดหายไปแทนที่จะยืนยันมัน
! เป็นเครื่องมือที่คมชาร์ป: มันปิดความเป็น null-safety ที่คอมไพเลอร์พยายามให้คุณ
บางครั้งมันสมควร (คุณมีความรู้ที่คอมไพเลอร์ไม่มี) แต่การใช้มันมากเกินไปจะนำเข้า null-crash bugs ที่ strictNullChecks ป้องกัน
เข้าถึง ?., ??, หรือ guard ที่ชัดเจนก่อน; ใช้ ! เฉพาะเมื่อคุณสามารถพิสูจน์ non-nullness ได้จริง
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค