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"
.
CodePudding user response:
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}`
This feature is available in Typescript since 4.1 with the addition of Template literal types and mapped type 'as' clauses