Skip to the solution
EasyFrontend10 min read

How does TypeScript handle null and undefined safely?

286 views

The problem

Question presented to candidate: "Null reference errors are one of the most common JavaScript crashes. How does TypeScript help you avoid them, and which operators and patterns do you use day to day to handle values that might be missing?"

What a strong answer should cover:

  • `strictNullChecks` (part of `strict`, since TypeScript 2.0) takes `null` and `undefined` out of every type, so "may be missing" must be written as `T | null` or `T | undefined`
  • Narrowing removes them: `!== null`, `== null` (matches both null and undefined), truthiness checks (and their trap with `0` and `""`), early returns
  • Operators: `??` falls back only on null/undefined, unlike `||`; `?.` short-circuits to `undefined`
  • Library signatures that can miss: `Array.prototype.find`, `Map.get`, and `NonNullable<T>`
  • The non-null assertion `!` only silences the compiler and does no run-time check
  • Narrowing limits: callbacks over a reassigned `let`, and `filter` needing an explicit type predicate before TypeScript 5.5

Code / implementation expected: Yes β€” a function returning `T | null`, the compiler error when it is used unchecked, and the `??` versus `||` difference.

  • optional
  • nullish

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptstrictNullChecks, narrowing, ?? versus || and the ! trap
TypeScriptLookups that can miss, NonNullable, filter and closures

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 12 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What are access modifiers in TypeScript classes?

Continue