Skip to content

dictionaryGuard()

ts
function dictionaryGuard<Key, Value>(keyGard, valueGuard): Guard<Partial<Record<Key, Value>>>

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
Key extends string
Value

Parameters

ParameterTypeDescription
keyGardGuard<Key>validates every key
valueGuardGuard<Value>validates every value

Returns

Guard<Partial<Record<Key, Value>>>

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

Examples

Validate a word dictionary:

ts
const isDictionary = dictionaryGuard(isString, isString)
isDictionary({ hello: 'world' }) // -> true

You can limit the set of keys; for example, to only allow lowercase strings:

ts
const isLowerCase = (data: unknown): data is Lowercase<string> =>
  typeof data === 'string' && data === data.toLowerCase()
const isDictionary = dictionaryGuard(isLowerCase, isString)
isDictionary({ hello: 'world' }) // -> true
isDictionary({ Hello: 'world' }) // -> false