Skip to content

equalsGuard()

ts
function equalsGuard<T>(...constants): Guard<T[number]>

Compares the input against a list of primitive values with the strict equality operator (===). The inferred type of the guard is that of a literal type; for example, equalsGuard('red') returns a Guard<'red'>. When called with multiple arguments, the guard will return true if the input equals to any of the provided values, and thus return a union type.

Type Parameters

Type Parameter
T extends readonly Primitive[]

Parameters

ParameterTypeDescription
...constantsTcompared against data with the === operator.

Returns

Guard<T[number]>

Examples

ts
const isRed = equalsGuard('red')
isRed('red') // -> true
isRed('blue') // -> false

const isOne = equalsGuard(1)
isOne(1) // -> true
isOne(2) // -> false

Commonly used in discriminated unions:

ts
const isResult = oneOfGuard([
 objectGuard({
   tag: equalsGuard('success')
 }),
 objectGuard({
   tag: equalsGuard('error')
  }),
])

If you pass in multiple values, the guard will validate a union type:

ts
const isLogLevel = equalsGuard('debug', 'info', 'warning', 'error')

When explicitly annotating unions, provide a tuple of the union members as type argument:

ts
const isColor = equalsGuard<['red', 'green', 'blue']>('red', 'green', 'blue')