Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Primitive and Special Types

The TypeScript undefined type

Reference for undefined in TypeScript: where it appears, optional properties and parameters, exactOptionalPropertyTypes, narrowing, void and default values.

undefined is the value JavaScript gives to anything that has not been set: an uninitialized variable, a missing property, a parameter that was not passed, or a function that returns nothing. In TypeScript undefined is also a type with that single value.

Optional markers (?) quietly add undefined to a type. Under strictNullChecks you must narrow before using such a value, which is why most "missing" cases are caught at compile time.

TypeScript
let maybe: string | undefined;     // starts as undefined
function greet(name?: string) {}   // name: string | undefined

Try it

TypeScript Where undefined comes from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Narrowing and defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
let a: undefined = undefined;
let b: number | undefined;
interface Box { value?: number }
function f(x?: number, y: number | undefined = 5): void {}
Form Description
undefined (type) Contains only the value undefined.
T | undefined Value may be absent; the property or argument must still be present.
prop?: T Property may be missing; reading gives T | undefined.
exactOptionalPropertyTypes Makes prop?: T mean "missing or T", so undefined must be added explicitly.

Usage notes

  • undefined vs void. void is for return types of functions whose result is ignored; undefined is a real value. A function typed () => void may be given one that returns something.
  • Indexing lies by default. Array and record lookups are typed as the element type even when out of range; enable noUncheckedIndexedAccess to get T | undefined.
  • Default parameters apply only for undefined, not for null. Passing undefined explicitly uses the default.
  • Optional vs | undefined. { a?: number } allows omitting a; { a: number | undefined } demands you write the key.
  • delete only works on optional properties, which makes absent keys representable.
  • JSON. undefined values and keys disappear in JSON.stringify; in arrays they become null.
  • Checks. x === undefined is precise; typeof x === "undefined" also works for undeclared globals without throwing.
  • Possible-undefined reads report TS18048 ("'x' is possibly 'undefined'").