0
0
Typescriptprogramming~5 mins

Never type and unreachable code in Typescript

Choose your learning style9 modes available
Introduction

The never type helps us catch code that should never happen. It also shows when some parts of the code can never run.

When a function always throws an error and never returns a value.
When you want to mark a part of code that should never be reached, like a default case in a switch.
When TypeScript can tell some code is unreachable and you want to understand why.
When you want to make your code safer by catching impossible cases.
Syntax
Typescript
function example(): never {
  throw new Error("This function never returns");
}

// unreachable code example
function check(value: string | number) {
  if (typeof value === "string") {
    console.log("It's a string");
  } else if (typeof value === "number") {
    console.log("It's a number");
  } else {
    // This else is unreachable
  }
}

The never type means the function never finishes normally.

Unreachable code is code that can never run because previous checks cover all cases.

Examples
This function never returns because it always throws an error.
Typescript
function fail(): never {
  throw new Error("Fail always");
}
This function never returns because it loops forever.
Typescript
function infiniteLoop(): never {
  while (true) {}
}
The else block is unreachable because x can only be string or number.
Typescript
function checkValue(x: string | number) {
  if (typeof x === "string") {
    console.log("String");
  } else if (typeof x === "number") {
    console.log("Number");
  } else {
    // unreachable code
  }
}
Sample Program

This program shows a function that always throws an error and a check function that handles string or number inputs. The else block is unreachable because all cases are covered.

Typescript
function errorMessage(message: string): never {
  throw new Error(message);
}

function checkInput(input: string | number) {
  if (typeof input === "string") {
    console.log(`Input is a string: ${input}`);
  } else if (typeof input === "number") {
    console.log(`Input is a number: ${input}`);
  } else {
    // This code is unreachable
    errorMessage("Unexpected input type");
  }
}

checkInput("hello");
checkInput(42);
OutputSuccess
Important Notes

Use never to make your code safer and clearer.

TypeScript helps find unreachable code to avoid mistakes.

Summary

never means a function never returns normally.

Unreachable code is code that cannot run because all cases are handled.

Using never helps catch errors early and write safer code.