re: Tag Your Unions Before You Wreck Your Unions VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION

You can "simplify" the type checking part by making the method part of your type definition and setting it's type to the string literal:

type Get = {
  method: 'GET';
...

Inside of an if/switch-case that checks method typescript only allows access to the proper fields.
In case you cover all cases in a switch, inside default, the type of the variable will be never.
Typescript calls this "Discriminated Unions":
typescriptlang.org/docs/handbook/a...
(There is no way to link directly to the section, you need to search for the term on the page.)

code of conduct - report abuse