oneOfGuard()
ts
function oneOfGuard<T>(...guards): (data) => data is T[number]
Executes guards
in order and returns true if any guard matches. The result type is a union.
Type Parameters
Type Parameter |
---|
T extends readonly unknown [] |
Parameters
Parameter | Type | Description |
---|---|---|
...guards | { [K in string | number | symbol]: Guard<T[K<K>]> } | any of these guard functions must match the data. |
Returns
Function
a guard function that validates unions
Parameters
Parameter | Type | Description |
---|---|---|
data | unknown | data to be validated |
Returns
data is T[number]
true
if the data is in the specified union
Examples
Commonly used in discriminated unions:
ts
const isResult = oneOfGuard([
objectGuard({
tag: equalsGuard('success')
}),
objectGuard({
tag: equalsGuard('error')
}),
])
When explicitly annotating oneOfGuard
, provide a tuple of the union members as type argument:
ts
const isId = oneOfGuard<[string, number]>(isString, isNumber)
Due to a limitation of TypeScript, it is not possible to write unionGuard<string | number>()
or equalsGuard<'red' | 'green' | 'blue'>()
. Therefore, it is generally recommended to omit the type arguments for union types and let TypeScript infer them.