TypeScript Exhaustiveness Checking

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 discriminated union 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.

Notice that there is a red line in line 347, it is due to missing triangle case in switch block.

This is the error shown in the code.

After adding triangle case in line 346, the error disappeared.

Examples

Leave a Reply