Skip to content

dictionary()

ts
function dictionary<K, V>(parseKey, parseValue): Parser<Partial<Record<K, V>>>

Dictionaries are objects where all properties are optional and have the same type. In TypeScript, this can be represented by Partial<Record<string, ?>>.

Type Parameters

Type Parameter
K extends string
V

Parameters

ParameterTypeDescription
parseKeyParser<K>parses every key
parseValueParser<V>parses every value

Returns

Parser<Partial<Record<K, V>>>

a parser for a dictionary, of type Partial<Record<K, V>>

Examples

Validate a word dictionary:

ts
const parseDictionary = dictionary(isString, isString)
parseDictionary({ hello: 'world' }) // -> Success
parseDictionary({ hello: 1 }) // -> Failure

You can transform the keys and values; for example, to only allow lowercase strings:

ts
const parseLowerCase = (data: unknown): data is Lowercase<string> =>
  typeof data === 'string' ? failure('Not a string') : success(data.toLowerCase())
const parseDictionary = dictionary(parseLowerCase, parseLowerCase)
parseDictionary({ hello: 'world' }) // -> Success<{ hello: 'world' }>
parseDictionary({ Hello: 'world' }) // -> Success<{ hello: 'world' }>
parseDictionary({ hello: 'World' }) // -> Success<{ hello: 'world' }>