العامل اللاحقة ! يخبر المُترجم "أضمن أن هذه القيمة ليست null أو undefined هنا" — مما يزيل null/undefined من نوعها دون أي فحص وقت التشغيل.
ts
function () {
.(name!.());
}
العامل اللاحقة ! يخبر المُترجم "أضمن أن هذه القيمة ليست null أو undefined هنا" — مما يزيل null/undefined من نوعها دون أي فحص وقت التشغيل.
function () {
.(name!.());
}
إنه تأكيد وقت الترجمة فقط — مثل as، فهو لا يجري أي تحقق وقت التشغيل. إذا كنت مخطئاً، فسيؤدي ذلك إلى تعطل:
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-crash التي تمنعها strictNullChecks.
استخدم ?.، ??، أو حماية صريحة أولاً؛ استخدم ! فقط عندما تستطيع حقاً إثبات عدم الفراغية.