Skip to content

record ​

An object with arbitrary keys — a dictionary. All values are validated with one schema, and optionally the keys too.

Signature ​

ts
function record<V>(value: Schema<V>, msg?: Message): Schema<Record<string, V>>
function record<K extends string, V>(key: Schema<K>, value: Schema<V>, msg?: Message): Schema<Record<K, V>>

Parameters ​

ParameterTypeDescription
keySchema<K>Optional key schema: pipe(string(), pattern(...)), oneOf([...])
valueSchema<V>Value schema
msgMessageCustom message if the value is empty or not an object

Notes ​

  • Key and value errors are attached to that key's path: errors.ab.
  • If the key schema transforms the key (e.g. toLowerCase), data gets the transformed key.
  • Only own keys are read. A __proto__ key from JSON is safe — it doesn't change the result's prototype.

Error codes ​

CodeWhenDefault message
requiredThe value is emptyRequired
objectNot an object (or an array)Must be an object

Examples ​

Translations ​

ts
const title = record(oneOf(['ru', 'en', 'zh']), pipe(string(), maxLength(200)));
// Record<'ru' | 'en' | 'zh', string>

validate(title, { ru: 'Привет', en: 'Hello' }).valid; // true
validate(title, { de: 'Hallo' }).errors;              // { de: 'Must be one of: ru, en, zh' }

Quantities by product ID ​

ts
const cart = record(pipe(string(), pattern(/^\d+$/)), pipe(number(), integer(), min(1)));

validate(cart, { '15': 2, '42': 1 }).data; // { '15': 2, '42': 1 }

See also ​

  • object — an object with known fields
  • oneOf — restrict the keys