/combined-typescript-types/cover.jpg

Combined TypeScript Types

Sometimes you have two existing types and you need to combine them. An easy way to do this is built in in TypeScript. You can set a TypeScript type by setting its value to a template string which takes in existing types. The resulting type will consist of all possible combination of the provided types.

ts
type Cars = 'BMW' | 'VW' | 'Audi' // union type
type Drivers = 'Bob' | 'Billy' | 'John' // union type
type CarDrivers = `${Drivers} drives ${Cars}` // template literal type
const whoDrives: CarDrivers = "Bob drives BMW" // only allows the combined value

Here we have 9 types created in a single line from two existing types.