Exhaustive Switch in TypeScript
Hello, I am currently writing a little backend code with TypeScript, and I want to use some exhaustive switch to give back my client proper errors.
However, the types are not work as what I expected, can someone help me?
TS Playground: https://tsplay.dev/w29YrW
I don't understand why both
result1
on line 25 and result2
on line 42 are of type ErrorResult
but behaves differently when I switch on them.
How can I handle the errors properly?
Should I manually type the secondService
so that it returns ErrorResult<"not permitted" | "not found">
?TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
5 Replies
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
I can't check if my switch is exhaustive in your version, and also not able to know what are the errors that my service is going to return : (
Is ther service backend written by you?
I would say either yes or no. I am developing the service with some others, and I want to use the type system to check the errors. That's why I don't throw in my service and want an exhaustive switch.
note: The throw in the switch is actually throwing to tRPC, I want to use the errors returned by our service to throw different tRPC error codes.
Now we're using
ts-pattern
and I'm quite happy with that 🙂Ts-pattern looks really handy