Union Types - Advent of TypeScript

ยท

2 min read

The Christmas ๐ŸŽ„ season is now here and Santa ๐ŸŽ… is bringing many different seasonal learning opportunities for developers. Egghead did a great job on 2021 with their Holiday Course Extravaganza and now I'm enjoying doing type hero's new Advent of TypeScript.

I don't spend too much time these days refreshing or leveling up my TypeScript skills, I mostly on leverage types and solutions that already exist on the code bases that I work on. So I find this a perfect opportunity to level up my TS skills with some holiday-themed challenges.

As the time of writing this is December 2nd, the challenges started yesterday December 1st, but I didn't have the time to post about the first challenge, so today I will write two posts about the first and the second challenge.

Day one - Dec 1st

I strongly encourage you to try the first challenge on your own before reading the solution here.
Challenge: Christmas Cookies

The challenge

It's December 1st! That means it's almost time for the big day! Santa has a preparation regimen that involves, of course, eating lots of delicious cookies.

Santa's elves have provided Santa an API whereby Santa can submit his favorite cookie flavors. This year his favorites are:

  • ginger-bread

  • chocolate-chip

But the elves have some kind of fancy code-gen build step (built in Rust, of course), so all Santa needs to do is update the SantasFavoriteCookies type to accept either of his favorite cookies.

The code to complete

type SantasFavoriteCookies = 'ginger-bread' | 'chocolate-chip';

The tests

import { Expect, Equal } from 'type-testing';

type test_0_actual = SantasFavoriteCookies;
//   ^?
type test_0_expected = 'ginger-bread' | 'chocolate-chip';
type test_0 = Expect<Equal<test_0_actual, test_0_expected>>;

The solution

This challenge is about the SantasFavoriteCookies type to accept either of Santa's favorite cookies: 'ginger-bread' or 'chocolate-chip'. In TypeScript, you can achieve this by using a union type:

type SantasFavoriteCookies = 'ginger-bread' | 'chocolate-chip';

A union type in TypeScript allows a type to hold values of multiple specified types. You can define a union type by using the union operator |.

In this case, we are only including two string literals: 'ginger-bread' and 'chocolate-chip'. This means that a variable of type SantasFavoriteCookies can only have one of these two string values.

You can use any valid type in a union:

type MyUnion = string | number | boolean;

let xmas: MyUnion;

xmas = 'rudolph';   // Valid
xmas = 25;          // Valid
xmas = true;        // Valid

Hope you enjoyed today's TypeScript challenge by the Advent of TypeScript.
See you tomorrow in the next one!

ย