Today I Learned

hashrocket A Hashrocket project

TypeScript Union Types

Today I got a chance to try out the TypeScript union type. It looks like this.

interface FlashMessageWithSuccess {
  state: 'success';
  message: string;
}

interface FlashMessageWithFailure {
  state: 'failure';
  message: string;
}

export type FlashMessageInterface =
  | FlashMessageWithSuccess
  | FlashMessageWithFailure;

This lets me tell consumers of FlashMessageInterface that it is allowed to have two shapes: one with a state key of success and one with a state key of failure. I can use this to change how I present the flash message.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.