๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Never

The never type marks a function that never returns a value. A function with this type always throws an error.

A function that always throws

The fail function throws on every call. instanceof asks whether a value was built by a named class.

function fail(message: string): never {
  throw new Error(message);
}
try {
  fail("Something went wrong");
} catch (err) {
  if (err instanceof Error) {
    console.log("Caught: " + err.message);
  }
}

Never can stand in for a string

The first branch holds a call to a never function. The compiler accepts that call where a string is expected.

function fail(message: string): never {
  throw new Error(message);
}
const userName: string = "Ada";
const label: string = userName === "" ? fail("Name is required") : userName;
console.log(label);

Example

function fail(message: string): never {
  throw new Error(message);
}
function greet(name: string): string {
  if (name === "") {
    return fail("Name is required");
  }
  return "Hello, " + name;
}
console.log(greet("Ada"));

Key points

  • The return type never marks a function that cannot return a value.
  • Throwing an error is how a never function ends.
  • A value of type never can stand in for a value of any other type.
  • Exhaustiveness is the practice of proving that every case in a set is handled.

In this example, greet receives a valid name. The empty check fails, so the fail call never runs. The function builds the greeting text, and the log prints it.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What happens when a function typed never is called?