Below two code blocks are doing same job and the only difference is below second code block uses variadic tuple. Check the below links for more details.
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
const sendRequest = (url: string, method: HttpMethod) => {
switch (method) {
case 'DELETE':
break;
case 'GET':
break;
case 'POST':
break;
case 'PUT':
break;
default:
const exhaustiveCheck: never = method; // ✅ no error
throw new Error(`Unhandled case: ${exhaustiveCheck}`);
}
};
type Fruit = 'banana' | 'orange' | 'mango';
function exhaustiveCheck(param: never): never {
throw new Error('should not reach here')
}
function makeDessert(fruit: Fruit) {
switch (fruit) {
case 'banana': return 'Banana Shake'
case 'orange': return 'Orange Juice'
}
exhaustiveCheck(fruit) // ? ERROR! `mango` is not assignable
}
Exhaustiveness checking is a good feature when you use switch block. Assume that you need to check a value of variable which data type is union type as shown below screenshot.
Shape is a discriminatedunion which consists of three types named Circle, Square and Triangle.
kind field is shared in Circle, Square and Triangle types so that if developer forgets to use any of kind field value in switch block, TypeScript will error in coding-time.
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let big: bigint = 100n;
String
let color: string = "blue";
let fullName: string = 'Bob Bobbington';
let age: number = 37;
let sentence: string = `Hello, my name is ${fullName}.
I'll be ${age + 1} years old next month.`;
Arrays
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
When you remove [keyof T] section in line 169, you will see a big difference.
As you see in the following screenshot, it created an Union Object Type, but most of the field types are never. That's why, in order to list values of type, we need to have that deleted section.