Union types in Typescript

1. Replace enums

export enum Color {RED, BLUE, WHITE}
export enum Color {RED = ‘red’, BLUE = ‘blue’, WHITE = ‘white’}
export type Color = 'red' | 'white' | 'blue';
const myColor: Color = 'red';

2. Mark a property as optional

let user: User | undefined;
export type Optional<T> = T | undefined;let user: Optional<User>;

3. Union types as an alternative to inheritance

export type AuthAction = LoginAction
| LoginSuccessfulAction
| LoginErrorAction
| LogoutAction
| LogoutSuccesfulAction;



Google Developer Expert in Angular, Consultant and Trainer at http://www.angulartraining.com

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store