Advanced TypeScript #7: exhaustive switch with never
Here’s part 7 of 7 of the Advanced TypeScript series, where I share TypeScript patterns I’ve encountered in enterprise grade applications.
7. Exhaustive switch asserting type never
in default statement
When using enums or unions, it's possible to ensure every possible value is handled in a switch statement over it by using an assertNever(value: never)
function.
type PlatformType = 'MOBILE' | 'WEB';
function generateAnalyticsPlatform(platform: PlatformType) {
switch (platform) {
case 'MOBILE':
return 'mobile';
case 'WEB':
return 'web';
default:
assertNever(platform);
}
}
function assertNever(value: never) {
if (value) {
throw new Error(`Unexpected value "${value}"`);
}
}
import assert from 'node:assert';
import test from 'node:test';
[
{ platformValue: 'WEB', expected: 'web' } as const,
{ platformValue: 'MOBILE', expected: 'mobile' } as const,
].map(({ platformValue, expected }) => {
test(`generateAnalyticsPlatform(${platformValue}) outputs '${expected}'`, () => {
assert.equal(generateAnalyticsPlatform(platformValue), expected);
});
});
That's this week's pattern, you can get a sneak peek of the rest at codewithhugo.com/typescript-types-in-the-trenches/, or access the annotated source at github.com/HugoDF/real-world-ts.
Don't miss what's next. Subscribe to Deep in Software with Hugo: