TypeScript Has Template Literal Types

TypeScript Has Template Literal Types

If you know JavaScript template literals, TS Template Literal Types is exactly what you think it is.

I have been using TypeScript for a few years now, and while I am not a TypeScript expert yet, I feel I know it pretty well. And yet, TypeScript can still surprise me in many interesting ways, with one having happened today while going through the Total TypeScript training prepared by Matt Pocock.

I have learned that TypeScript supports Template Literal Types! If you are familiar with Template Literals (Template Strings) in JavaScript, then see if your intuition can fill in the blanks of what Template Literal Types are.

"Trust your feelings, Luke." - Obi-Wan Kenobi in Star Wars

Template Literal Types have been added to TypeScript in version 4.1 and, as the documentation says, when you use them with concrete literal types, they produce new string literal types by concatenating the contents.

// Conrete literal string type
type PositionType = 'top' | 'right' | 'bottom' | 'left'

// New string literal types created using Template Literal Type
type MarginPropertiesType = `margin-${PositionType}`
type PaddingPropertiesType = `padding-${PositionType}`

// Same as above without using Template Literal Type
type MarginPropertiesManualType =
  | 'margin-top'
  | 'margin-right'
  | 'margin-bottom'
  | 'margin-left'

type PaddingPropertiesManualType = 
  | 'padding-top'
  | 'padding-right'
  | 'padding-bottom'
  | 'padding-left'

This is fascinating because Template Literal Type becomes a powerful tool to reduce the need to manually write some of the types with all the permutations.

There are some more advanced real-world use cases provided in the official documentation, so I highly recommend checking those examples out!