Complete the code to declare a function that never returns.
function fail(): [1] { throw new Error('This function never returns'); }
The never type is used for functions that never return, such as those that always throw an error.
Complete the code to make the switch statement exhaustive using the never type.
type Color = 'red' | 'green' | 'blue'; function checkColor(c: Color) { switch(c) { case 'red': return 'Red'; case 'green': return 'Green'; case 'blue': return 'Blue'; default: const _exhaustiveCheck: [1] = c; return _exhaustiveCheck; } }
Using never in the default case ensures the switch is exhaustive. If a new color is added, TypeScript will warn.
Fix the error in the function that should never return but currently returns a value.
function errorFunction(): never {
[1] 'Error occurred';
}The function must throw an error to never return. Using throw stops execution and matches the never type.
Fill both blanks to create an exhaustive check function using the never type.
function assertNever(x: [1]): [2] { throw new Error('Unexpected value: ' + x); }
The parameter type is never and the function return type is also never because it always throws an error.
Fill all three blanks to handle all cases and use the never type for unreachable code.
type Shape = { kind: 'circle', radius: number } | { kind: 'square', size: number };
function area(s: Shape): number {
switch(s.kind) {
case 'circle':
return Math.PI * s.radius * s.radius;
case 'square':
return s.size * s.size;
default:
return [1]([2]);
}
}
function [3](x: never): never {
throw new Error('Unexpected shape: ' + x);
}The assertNever function is called with s in the default case to ensure all cases are handled. It accepts a never type and throws an error.