Classes
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 |
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. |
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 |
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. |
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'
}