Skip to content
BENIBIX Learn

Null Safety

Also known as Null Safe, Strict Null Checks, Optional Type

A type rule. A value can be empty only if its type says so.

Think of it like

Think of it like a gift box. The label must say if it might be empty.

Example

Jack sets a name of type string to null. TypeScript refuses before the app runs, so the crash never reaches a user.

Why it matters

Reading a value that is not there is one of the commonest crashes in software. Null safety catches it before the code runs.

Definition

Null safety is a type rule that stops a value from being empty unless you say it may be. In a null-safe language, a string is always a real string, never null. If a value might be missing, its type says so, and you must check before using it. That removes a whole class of crash where code reads a value that is not there. Kotlin, Swift, Rust and TypeScript in strict mode all work this way.

Example code

typescript
let name: string = null;
// Type 'null' is not assignable to type 'string'.
In strict mode, a string may not be empty by accident.

Common mistake

Silencing the check with a ! or a cast to make the error go away. The crash then comes back at run time.

Key takeaways

  1. 1
    Never empty by default. A string is a string.
  2. 2
    Say when it may be. The type shows it.
  3. 3
    Check before use. The checker insists.