Files
typebox/docs/types/mapped.md

1.1 KiB

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

Mapped Types

TypeBox supports mapped types with the Mapped function. This function accepts two arguments, the first is a union type typically derived from KeyOf, the second is a mapping function that receives a mapping key K that can be used to index properties of a type. The following implements a mapped type that remaps each property to be T | null.

const T = Type.Object({
  // type T = {
  x: Type.Number(), //   x: number,
  y: Type.String(), //   y: string,
  z: Type.Boolean(), //   z: boolean
}); // }

const M = Type.Mapped(Type.KeyOf(T), (K) => {
  // type M = { [K in keyof T]: T[K] | null }
  return Type.Union([Type.Index(T, K), Type.Null()]); //
}); // ... evaluated as
//
// const M: TObject<{
//   x: TUnion<[TNumber, TNull]>,
//   y: TUnion<[TString, TNull]>,
//   z: TUnion<[TBoolean, TNull]>
// }>

Back to Home