Skip to content
von Schappler edited this page Oct 27, 2024 · 1 revision

How union types work

To understand what are unions and how they work, lets assume a single scenarion in which we are creating a user, with an access role. If we wish to strict this access role to be either guest, member or admin, this can be done easily with unions types - a combination of literal types - in TypeScript.

The snippet of code below exemplifies how this could be achieved.

type UserRole = 'guest' | 'member' | 'admin';

let userRole: UserRole = 'guest';

Clone this wiki locally