DEV Community

Cover image for Exhaustive Type Checking with TypeScript!

Exhaustive Type Checking with TypeScript!

Babak on April 08, 2019

Introduction Wouldn't it be great if you could spot a bug the moment you wrote it down? That's what static type analysis is all about. C...
Collapse
 
codefinity profile image
Manav Misra

You can see here that this part of the 'Beta manual' is missing. Maybe you want to contribute there by doing a pull request?

Collapse
 
vimkin profile image
Vadim Kalinin

I came up with the idea, that throwing an error inside the function solely created for this purpose (in your case exhaustiveCheck) feels somehow odd. Throwing the error directly (e.g. UnsupportedValueError(x)) or declaring the output type for the function explicitly feels more natural. For interested, both cases are described in detail here: 2ality.com/2020/02/typescript-exha....

imho using a helper library that replicates the switch for exhaustive checking which is already supported by the typescript feels unnecessary.

Collapse
 
mindplay profile image
Rasmus Schultz

The error message you get with this "trick" is only useful if you know why you're getting it - adding a function just for the purposes of triggering a confusing compiler error?

I like this approach better:

dev.to/housinganywhere/matching-yo...

This gives more meaningful error messages, with a function that actually does something - and resembles the matching pattern from functional languages quite well. 👍

Collapse
 
ionutgi profile image
IonutGI • Edited

Exhaustiveness checking seems like the 'default' behavior for the above switch statements.

Great article though.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Yes, but it’s more explicit. Even in C# (which doesn’t have exhaustiveness checking like TypeScript), the best practice is to throw an error in the default case that says “unexpected case”. The benefit of TS is that it can catch those unexpected cases at compile time too! :)

Collapse
 
ionutgi profile image
IonutGI

Agreed. Thanks a lot.

Collapse
 
mrispoli24 profile image
Mike Rispoli

I've been trying this method myself but my typescript compiler won't let me use the never even if there is no possible way for it to be hit. Is there a tsconfig option missing here?