TypeScriptBasic types

null and undefined

The types for the absence of a value, controlled by strictNullChecks.

On this page

Example

#
TypeScript
function findUser(id: number): { name: string } | null {
  return id === 1 ? { name: 'Emma' } : null
}

const user = findUser(2)
console.log(user?.name ?? 'Guest')
console.log(findUser(1)?.name)
Result
Guest
Emma

Definition and usage

#

In TypeScript, null and undefined have their own types. With the strictNullChecks option turned on (part of strict mode), you can’t assign them to a variable typed string or number. If a value might not exist, you have to say so explicitly: string | null.

That way the compiler forces you to handle the missing value. Before you read a property, you have to check that the object exists, or use the ?. and ?? operators.

A convention in many projects: undefined means “not set” (for example an omitted optional field), and null means “deliberately empty” (for example no avatar).

Syntax

#
Syntax
let value: string | null = null
let optional: number | undefined

More examples

#
The compiler forces a check
TypeScript
const avatar: string | null = null
console.log(avatar.length)
// Error: 'avatar' is possibly 'null'.

Good practices

#
  • Keep strictNullChecks turned on. It’s one of the most valuable protections against “cannot read properties of undefined” errors.
  • The ?? operator returns the right-hand side only for null and undefined, not for 0 or an empty string.

Related entries

#

Spotted a mistake or missing an example? Write to us.