'Create matrix type from two discriminated unions

I have two discriminated unions in TypeScript:

type Person = "alice" | "bob"
type Number = 1 | 2

From these two discriminated unions, how can I create a new discriminated union from every possible combination:

type Desired = "alice-1" | "bob-1" | "alice-2" | "bob-2"

Ideally Desired is not hardcoded as Person and Number could get quite large. If needed, Number could be the string union "1" | "2".



Solution 1:[1]

You can just apply template literal types and you'll get the the desired type:

type Person = "alice" | "bob"
type Number = 1 | 2

type Desired = `${Person}-${Number}`

Playground Link

This feature is available in Typescript since 4.1 with the addition of Template literal types and mapped type 'as' clauses

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1