Safe collection lookups
Prevent property access on missing lookup results.
TypeScript · Const
strictNullChecks controls whether null and undefined are treated as distinct types. When enabled, TypeScript requires code to handle possibly absent values before using them as definite values.
When enabled, strictNullChecks gives null and undefined separate types instead of treating them as valid values for every type. Code must account for those possibilities before using a value where a concrete type is required, typically through narrowing or an explicit union.
{"compilerOptions":{"strictNullChecks":true}}// tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true
}
}
const users = [{ name: "Ada" }];
const user = users.find(candidate => candidate.name === "Grace");
if (user) {
console.log(user.name);
}With strict null checking enabled, find returns a value that may be undefined, so the guard is required before reading name.
Prevent property access on missing lookup results.
Make nullable API responses explicit in types.
Expose absence-related defects during compilation.
With strictNullChecks enabled, null and undefined are distinct types rather than being ignored. A value that may contain either cannot be used where a concrete value is required until the possibility is handled.
Follow-up: How would you represent a nullable number? Use the union type number | null, then narrow it before operations that require number.
Array.find is modeled as returning S | undefined when strict null checking is enabled. Therefore, callers must check the result before accessing its properties or passing it to code that expects S.
Follow-up: What is the practical benefit? The compiler exposes missing-result paths that could otherwise become runtime failures.
With the option disabled, null and undefined are effectively ignored by the type system, so code can use values as though they were always present. Enabling it makes those absence cases visible during compilation.
Follow-up: What should a project do when migrating? Add the checks or explicit unions required by the newly reported errors, rather than suppressing them indiscriminately.
strictnullundefinedArray.find