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 validatesRecord<string, V>
. WhennoUncheckedIndexedAccess
is enabled, TypeScript understands that a value retrieved with a string the value can beundefined
. However, the value is not semantically identical toPartial<Record<string, V>>
. - When the key is a subset of
string
, it validatesPartial<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
Parameter | Type | Description |
---|---|---|
keyGard | Guard <Key > | validates every key |
valueGuard | Guard <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