Menu

Template Literal Types and Branded Types

Lesson 5: Template Literal Types and Branded Types

What are template literal types?

Template literal types build string types from other string types, using the same syntax as JavaScript template strings.

Type Matches
`order:${string}` Any string starting with order:
`${Slot}-${Day}` Every combination, e.g. 'morning-mon'
`${number}px` '16px', '2.5px'
`QC-${number}` 'QC-1042'

Example

@@CODE_BLOCK_0@@

What is a branded type?

Structural typing treats two string types as identical, so a CustomerId can be passed where a ProductId is expected. A brand adds an invisible marker so TypeScript treats them as different.

@@CODE_BLOCK_1@@

How it works

  • Template literal unions expand into every combination, so keep the inputs small.
  • Brands exist only in the type system. At runtime, a ProductId is a plain string.
  • Create branded values in one place (a constructor function that validates), so the as cast is controlled.
  • Brands are especially useful for IDs, money units (paise versus rupees), and validated strings such as emails.

Common mistakes

Mistake Effect Fix
Huge template literal combinations Slow compiler, errors about union size Keep input unions small, or use ${string}
Casting to a brand everywhere Brands lose their value Create branded values only in validating helpers
Expecting brands at runtime They do not exist Validate data at runtime separately

Key takeaways

  • Template literal types describe string patterns and generate combinations.
  • Branded types stop structurally identical values, such as different IDs, from being mixed up.

Try it: Create branded Rupees and Paise types with conversion helpers, and write a function that only accepts Paise.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details