Strict null checks
suggest changeWith strictNullChecks, null and undefined are distinct types and are not silently accepted by every other type. Narrow nullable values before access instead of scattering non-null assertions.
interface User {
name: string;
}
function uppercaseName(user: User | undefined): string {
return user?.name.toUpperCase() ?? "ANONYMOUS";
}
function requireUser(user: User | undefined): asserts user is User {
if (user === undefined) throw new Error("user is required");
}
Use the postfix non-null assertion (value!) only when an external invariant truly guarantees a value and cannot be expressed in the type system. It emits no runtime check. Also remember that an absent optional property and a present property whose value is undefined can behave differently with operations such as the in operator; exactOptionalPropertyTypes distinguishes those cases in the type system.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents