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...
For further actions, you may consider blocking this person and/or reporting abuse
You can see here that this part of the 'Beta manual' is missing. Maybe you want to contribute there by doing a pull request?
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.
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. 👍
Exhaustiveness checking seems like the 'default' behavior for the above switch statements.
Great article though.
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! :)
Agreed. Thanks a lot.
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?