Typescript never
Created By: chatGPT
Never is a special type in TypeScript that represents values that never occur. It is often used in functions that throw exceptions or have infinite loops. Use this type when you want to indicate that a function is not supposed to return a value because it will terminate the program. For example, you can use the never type when defining a function that never returns a value due to throwing an error or a function that enters an infinite loop.
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
console.log('This is an infinite loop.');
}
}
// Usage
throwError('Something went wrong!');
infiniteLoop();
The never type can also be used in union types to specify that a certain condition will not be met. For instance, you could use it in a function that checks for an exhaustive set of values, ensuring that any unexpected cases trigger a compile-time error.
type Shape = 'circle' | 'square';
function getArea(shape: Shape): number {
switch (shape) {
case 'circle':
return Math.PI * 5 * 5; // Assume radius is 5
case 'square':
return 5 * 5; // Assume side length is 5
default:
const _exhaustiveCheck: never = shape; // Trigger an error if any case is missed
throw new Error(`Unknown shape: ${shape}`);
}
}
// Usage
getArea('circle');