Skip to main content
In TypeScript, undefined is both a primitive data type and a literal value representing an uninitialized state or a missing property. At runtime, it behaves identically to JavaScript’s undefined, but within the TypeScript type system, its assignability and behavior are strictly governed by compiler configurations.

Type Annotation and Assignability

As a type, undefined can be explicitly annotated. Its assignability depends entirely on the strictNullChecks compiler option in tsconfig.json.
  • strictNullChecks: true (Strict Mode): undefined is its own distinct type. It cannot be assigned to other types (like string or number). It is only assignable to undefined, any, unknown, and void.
  • strictNullChecks: false: undefined becomes assignable to almost all other types (acting as a universal subtype). This effectively bypasses the type system for uninitialized values, which often leads to runtime errors.

Optional Modifiers

TypeScript provides the ? token to denote optional properties in interfaces/types and optional parameters in functions. Applying this modifier implicitly injects | undefined into the type union.
Note on exactOptionalPropertyTypes: If this compiler flag is enabled, TypeScript distinguishes between a property being entirely absent versus being explicitly set to undefined. Under this flag, timeout?: number means the key can be omitted, but { timeout: undefined } will throw a type error unless explicitly typed as timeout?: number | undefined.

Type Narrowing

When a variable is typed as a union containing undefined, the type system requires explicit narrowing (type guarding) before allowing operations specific to the non-undefined types.

Distinction from void

While a function that returns nothing implicitly returns the value undefined at runtime, the TypeScript types void and undefined are semantically distinct.
  • void indicates that a function’s return value does not exist or should be ignored by the caller.
  • undefined as a return type explicitly states that the function evaluates to the undefined value.
As of TypeScript 5.1, functions explicitly typed to return undefined are allowed to omit the return statement entirely. This aligns the control flow behavior more closely with void while maintaining the strict type signature.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More