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.
let maybe: string | undefined; // starts as undefined function greet(name?: string) {} // name: string | undefined
Try it
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.
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
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
undefinedvsvoid.voidis for return types of functions whose result is ignored;undefinedis a real value. A function typed() => voidmay 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
noUncheckedIndexedAccessto getT | undefined. - Default parameters apply only for
undefined, not fornull. Passingundefinedexplicitly uses the default. - Optional vs
| undefined.{ a?: number }allows omittinga;{ a: number | undefined }demands you write the key. deleteonly works on optional properties, which makes absent keys representable.- JSON.
undefinedvalues and keys disappear inJSON.stringify; in arrays they becomenull. - Checks.
x === undefinedis precise;typeof x === "undefined"also works for undeclared globals without throwing. - Possible-undefined reads report TS18048 ("'x' is possibly 'undefined'").