Loading lessons...
Null, Undefined & Void
Null, Undefined & Void
Understanding how missing values and return types work in TypeScript is critical for writing robust code.
Types Overview
undefined: Uninitialized variable or missing property.null: Intentional absence of any object value.void: Return type of functions that do not return a value.
strictNullChecks Setting
When strictNullChecks is enabled in tsconfig.json (recommended):
let name: string = "Alice";
// name = null; // Error! Type 'null' is not assignable to type 'string'.
let optionalName: string | null = null; // Allowed with Union type!
Void vs Never
// Returns nothing -> void
function logMessage(msg: string): void {
console.log(msg);
}
// Never finishes normally -> never
function fail(): never {
throw new Error("Fatal failure");
}
TL;DR
voidis used for functions with no return statement.- Enable
strictNullChecksto force explicit handling ofnullandundefined. - Use union types (
string | null) to model optional or nullable values.