Discussion on: Tag Your Unions Before You Wreck Your Unions

karfau profile image
Christian Bewernitz

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":
(There is no way to link directly to the section, you need to search for the term on the page.)