Process Exit and Terminal Functions
You'll learn: How to type functions like process.exit() and custom panic handlers that terminate program execution and never return control to the caller.
What Are Terminal Functions?
In programming, some functions are "terminal" — they end the entire program or throw control flow to a completely different context, never returning to where they were called. Think of them like emergency exits in a building: once you go through, you're not coming back through that door.
Common examples include:
process.exit()in Node.js- Custom
panic()orfatal()error handlers - Functions that always throw exceptions
Why Type These as never
These functions should return never because they literally never give back control flow. The compiler can use this information to understand that code after calling them is unreachable.
// Typing a panic handler
function panic(message: string): never {
console.error(`FATAL: ${message}`);
process.exit(1);
}
function divide(a: number, b: number): number {
if (b === 0) {
panic("Division by zero");
// TypeScript knows this line is unreachable
}
return a / b;
}
Terminal Functions in Control Flow
When TypeScript sees a never-returning function, it knows that branch terminates:
function assert(condition: boolean, message: string): asserts condition {
if (!condition) {
panic(message); // never returns
// No need to throw here — panic never comes back
}
}
Notice that panic() satisfies the assertion function's requirement to terminate the false branch completely.
Typing process.exit() Wrappers
function exitWithError(code: number, message: string): never {
console.error(message);
process.exit(code); // Node.js built-in, never returns
}
// Usage makes dead code obvious
function loadConfig(): string {
const config = process.env.CONFIG_PATH;
if (!config) {
exitWithError(1, "CONFIG_PATH not set");
// TypeScript knows config is still string | undefined here
// but this line never executes
}
return config; // Error: might be undefined
}
Key Takeaway: Type functions that terminate program execution with never return types — this lets TypeScript's control flow analysis correctly understand that subsequent code is unreachable and helps catch logical errors where you assumed termination would narrow types.