We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Super Set Unions

So we know we can drastically narrow a primitive type like "number" by using a union of literal types. For example, maybe only 3 error codes are valid:

type ErrorSlugs = "OK" | "NOT_FOUND" | "INTERNAL_ERROR";

This works great if these are the only valid error codes, but what if:

  1. Any string can be used as an error slug
  2. "OK", "NOT_FOUND", and "INTERNAL_ERROR" are the most common values and we like to have them show up in autocomplete

TypeScript has a hacky way for us to express this: super set unions.

type ErrorCodes = "OK" | "NOT_FOUND" | "INTERNAL_ERROR" | (string & {});

You might be wondering,

"Why wouldn't I just use string - the set of allowed values is the same?"

And you're right, but there's one subtle difference. By adding (string & {}), TypeScript won't change which values are allowed. Any string is allowed. But it will still give us autocomplete in our editor for the values "OK", "NOT_FOUND", and "INTERNAL_ERROR".

Assignment

At Support.ai, we're building a system to allow users to update their employment status. We'll give them the options for 3 common work preferences: employed, unemployed, and student, but we need to allow for custom states as well.

Update the EmploymentStatus type. It should be a super set union that includes:

  • The expected "default" strings: employed, unemployed, and student
  • Any other string value