Files
typebox/docs/types/template-literal.md

1.3 KiB

Home | Installation | Usage | Types | Values | Syntax | TypeRegistry | TypeCheck

Template Literal Types

TypeBox supports template literal types with the TemplateLiteral function. This type can be created using a syntax similar to the TypeScript template literal syntax or composed from exterior types. TypeBox encodes template literals as regular expressions which enables the template to be checked by Json Schema validators. This type also supports regular expression parsing that enables template patterns to be used for generative types. The following shows both TypeScript and TypeBox usage.

// TypeScript

type K = `prop${"A" | "B" | "C"}`; // type T = 'propA' | 'propB' | 'propC'

type R = Record<K, string>; // type R = {
//   propA: string
//   propB: string
//   propC: string
// }

// TypeBox

const K = Type.TemplateLiteral("prop${A|B|C}"); // const K: TTemplateLiteral<[
//   TLiteral<'prop'>,
//   TUnion<[
//      TLiteral<'A'>,
//      TLiteral<'B'>,
//      TLiteral<'C'>,
//   ]>
// ]>

const R = Type.Record(K, Type.String()); // const R: TObject<{
//   propA: TString,
//   propB: TString,
//   propC: TString,
// }>

Back to Home