Colleagues and I have been wanting to make validators to assert values to be of specific subtypes, e.g. a union of specific strings, and narrow the type accordingly. We've been going over the docs here for that but it just isn't clear to us, sorry. We feel the meaning of most of the internal ow type names (Predicate, BasePredicate, Validator, ReusableValidator, Main, etc) is a little lost on us and this doesn't help us make sense of the relevant API.
type AB = 'a' | 'b';
const data = getData();
ow(data, ow.object.partialShape({
letter: ow.string.oneOf(['a', 'b'])
}));
data.letter; // string, but we want AB
We've been trying various angles but the types never "click". Given the usual quality/DX of your libraries, we would expect there's some super simple factory function to call with a validator and generic type param, but we can't seem to cobble that together. The closest we've come is finding these APIs:
function isAB(value: unknown): value is AB {...}
class ABPredicate extends Predicate<AB> {
constructor() {
super('string');
this.addValidator(ow.create<AB>(isAB));
}
}
const ab: BasePredicate<AB> = {
[testSymbol]: ow.string.is(isAB),
};
The goal being:
const data: unknown;
ow(data, ow.object.partialShape({ letter: ouchAB }));
data.letter; // AB, not just string
Sorry if it's a stupid question but we'd like to stop fumbling around with it and just ask a more seasoned user or maintainer. How do we properly (e.g. a helpful failure message isn't even considered yet in our examples so far, but it should be done) and concisely (as little as possible boilerplate) make a validator to assert values and narrow the asserted type?
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too