@recubed/object-satisfies
v0.1.2
Published
key-based object validation
Downloads
6
Maintainers
Readme
object-satisfies
Tiny helper library written to simplify the task of fine-grained object validation.
Pretty much what you can do with ramda/where
or lodash/conforms
except that it's
smaller, prioritizes typings and makes field-level predicates aware of field existence (not just emptiness).
Given an arbitrary object, e.g.:
const scenario = {
a: 42,
b: 'ohai',
}
object-satisfies
allows key-based predicate composition, i.e.:
import satisfies from '@recubed/object-satisfies';
const spec = satisfies({
a: x => x === 42,
b: x => typeof x === 'string',
// c is optional and not in the 'scenario' object, object-satisfies
// lets you run a predicate regardless, additionally - field existence flag is
// added to the list of predicate arguments;
c: (x, found) => !found
})
const outcome = spec(scenario);
console.log(outcome); // true
Please note that type-wise, example above will only compile because the type of scenario
object is
unavailable at the time spec
argument is defined. To overcome this limitation one would need
to specify generic argument explicitly, like this:
import satisfies from '@recubed/object-satisfies';
const spec = satisfies<typeof scenario>({
a: x => x === 42,
b: x => typeof x === 'string',
c: (x, found) => !found
});
...however, if validation of explicitly typed "scenario object" against a spec argument is performed one needs to make sure the former is a superset (key-wise) of the latter, optional properties do count. To fix the compilation error caused by the piece of code above following type definition would need to be provided:
type Scenario = {
a: number;
b: string;
c?: () => {};
};
const scenario: Scenario = {
a: 42,
b: 'ohai',
};
See tests for additional use cases / behaviours.