TypeScript·Advanced·Coding·1 min read
How do you enforce exhaustive handling?
Short interview answer
Use a switch on the discriminator and pass the default value to an assertNever function or assign it to never. Adding a new union member then creates a compile error at every non-exhaustive branch.
Example
function assertNever(x: never): never { throw new Error('Unhandled: ' + JSON.stringify(x));}
switch (result.status) { case 'ok': return result.data; case 'error': return result.message; default: return assertNever(result); // compile error if a case is missing}Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.