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
and:
- Create a
throwErrorfunction that throws and returnsnever - Create a
parseNumberfunction that converts a string to a number, usingthrowError("Invalid number")if the input can't be parsed - Create an
ensurePositivefunction that returns the number if positive, or usesthrowError("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).