Capítulo 7 de 61

Chapter 7: Template Literals

Core Idea

z.templateLiteral() (introduced in Zod 4) builds a schema from a mix of literal strings and sub-schemas, mirroring TypeScript's template literal types, and validates that the input matches the resulting string pattern.

Key Concepts

  • z.templateLiteral([...parts]): each part is either a literal (string/number/etc.) or a schema whose inferred type is assignable to string | number | bigint | boolean | null | undefined.
  • Inferred type mirrors TS template literal types: the schema's output type is the same union TypeScript would infer from the equivalent template literal type.

Code Examples

const schema = z.templateLiteral([ "hello, ", z.string(), "!" ]);
// type: `hello, ${string}!`

z.templateLiteral([ "high", z.literal(5) ]);
// `high5`

z.templateLiteral([ z.nullable(z.literal("grassy")) ]);
// `grassy` | `null`

z.templateLiteral([ z.number(), z.enum(["px", "em", "rem"]) ]);
// `${number}px` | `${number}em` | `${number}rem`
  • What it demonstrates: composing literal segments with typed sub-schemas (including enums and nullable schemas) into one pattern.

Key Takeaways

  1. Use z.templateLiteral() when a string's valid shape is naturally expressed as a template (e.g. CSS values like ${number}px), instead of a hand-written regex.
  2. Any schema segment must resolve to a primitive-compatible type — you can't embed an object or array schema in a template literal.
  3. The output type tracks TypeScript's own template literal type inference, so downstream code gets a precise union type, not just string.

Connects To

  • Literals: template literals are literal segments plus schema segments strung together.
  • Enums: enum schemas are common template literal segments (e.g. unit suffixes).