Strict null checks

suggest change

With 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents