Class

Guard

Guard()

Constructor

# new Guard()

View Source guard.ts, line 16

Classes

Guard

Methods

# static narrow(n)

Creates a new guard that uses a narrow function. A little shortcut for new Guard(narrow(...)).

Parameters:
Name Type Description
n

Narrower

View Source guard.ts, line 110

Guard

Example
import { Guard } from 'narrow-minded'
const myGuard = Guard.narrow(['string', 'number'])
myGuard.satisfied(['horse', 42]) // => true

# and(other)

Creates a new guard that will satisfy the constraints of this AND other. Useful for combining primitive narrows with more complex type checking.

Parameters:
Name Type Description
other

Another Guard or a Narrower/NarrowerFunction which will be wrapped into a Guard automatically.

View Source guard.ts, line 160

Guard

Example
const myGuard = Guard.narrow({ type: 'string' }).and(
	(u: unknown): u is { type: 'this' | 'that' } =>
		['this', 'that'].includes((u as any).type),
)

# build(p)

An identity function that returns the value passed to it. Useful for defining objects that satisfy this guard using type inference.

Parameters:
Name Type Description
p

View Source guard.ts, line 145

p

# satisfied(u)

Runs the guard's narrowing function to validate the unknown value's type. Operates as a type predicate so conditional blocks infer this structure.

Parameters:
Name Type Description
u

The unknown value.

View Source guard.ts, line 137

A type predicate that u satisfies this guard.

Example
const myGuard = Guard.narrow({
	name: 'string',
	values: ['number'],
})

const good: unknown = { name: 'Horse', values: [1, 2] }
if (myGuard.satisfied(good)) {
	console.log('Good ' + good.name)
	// => 'Good Horse'
}

const bad: unknown = { name: 42, values: 'Nope' }
if (!myGuard.satisfied(bad)) {
	console.log('Bad ')
	// => 'Bad'
}