Skip to content

dictionaryGuard()

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

Dictionaries are objects that map strings to other values. *

Due to how TypeScript works, this function has two behaviors at the type level, depending on Key (At runtime, it always behaves the same):

  • When the key is string, it validates Record<string, V>. When noUncheckedIndexedAccess is enabled, TypeScript understands that a value retrieved with a string the value can be undefined. However, the value is not semantically identical to Partial<Record<string, V>>.
  • When the key is a subset of string, it validates Partial<Record<K, V>>. If the properties were not marked as optional, TypeScript would assume that all keys map to values.

Type Parameters

Type Parameter
Key extends string
Value

Parameters

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

Returns

Guard<string extends Key ? Record<Key, Value> : Partial<Record<Key, Value>>>

a guard for a dictionary

Examples

Validate a 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