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 these exported functions:
throwError(message: string): neverβ always throws an error using the given messageparseNumber(value: string): numberβ turn a string into a number; if the value cannot be parsed, callthrowErrorwith the exact messageInvalid number; otherwise return the numberensurePositive(value: number): numberβ return the number when it is zero or positive; if it is negative, callthrowErrorwith the exact messageNumber must be positive
Required exports
throwError, parseNumber, ensurePositiveCompletion criteria
throwError('Test error')throws with messageTest errorparseNumber('42')returns42parseNumber('not-a-number')throws with messageInvalid numberensurePositive(5)returns5ensurePositive(0)returns0(zero is allowed)ensurePositive(-1)throws with messageNumber must be positive
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.