The never Type and Impossible States
Model unreachable code and impossible values with never.
The never Type
never is the empty type — it represents values that can never occur. No value is assignable to never (except never itself). It marks situations that should be impossible.
// You cannot create a value of type never
function crash(): never {
throw new Error('boom');
}
try { crash(); } catch (e) { console.log('caught'); }Functions That Never Return
A function that always throws never returns normally, so its return type is never. This tells callers (and the compiler) that execution stops here.
function fail(message: string): never {
throw new Error(message);
}
try { fail('invalid'); } catch (e) { console.log('handled'); }All lessons in this course
- Understanding unknown vs any
- The never Type and Impossible States
- The void Type in Functions
- Type-Safe Handling of unknown