What is a template literal type, and how does its syntax resemble a JavaScript template literal?
Short answer
A template literal type uses the same backtick syntax as a runtime template literal, but with TYPES embedded inside `${...}` instead of values — it produces a new string literal type (or union of them) built from combining literal text with the possible values of the embedded…
Advertisement
AModel answer
A template literal type uses the same backtick syntax as a runtime template literal, but with TYPES embedded inside `${...}` instead of values — it produces a new string literal type (or union of them) built from combining literal text with the possible values of the embedded type(s).
type Greeting = `Hello, ${string}!`;
const a: Greeting = 'Hello, Sam!'; // OK
// const b: Greeting = 'Hi, Sam!'; // Error: doesn't match the patternReal-world example
Constraining a string parameter to follow a specific required format, like a greeting or a CSS custom property name.
Likely follow-ups
- What happens if you embed a UNION type (not just 'string') inside a template literal type?
Related topics