The Never Type

Never Type
πŸ‘¨β€πŸ’Ό Some functions never return. Not because they return void (nothing), but because they can't returnβ€”they throw an error or run forever.
function fail(message: string): never {
	throw new Error(message)
}
TypeScript uses this to mark code paths that can't continue. A never function is one that always throws or exits early.
🐨 Open
index.ts
and:
  1. Create a throwError function that throws and returns never
  2. Create a parseNumber function that converts a string to a number, using throwError("Invalid number") if the input can't be parsed
  3. Create an ensurePositive function that returns the number if positive, or uses throwError("Number must be positive") if negative
The key learning here is that parseNumber and ensurePositive should use the throwError function rather than throwing directly. This demonstrates how TypeScript's flow analysis understands that code after a never-returning function call is unreachable.
Number(value) converts a string to a number. If the string can't be parsed, it returns NaN (Not a Number). Check for NaN using Number.isNaN(result).

Please set the playground first

Loading "The Never Type"
Loading "The Never Type"