I’m trying to write a function createValidation
which composes predicates into final validator function. Here is usage example:
const validateString = createValidation(
[(value: unknown): value is string => typeof value === 'string', 'Value is not a string'],
[(value: string) => value.length > 0, 'String can not be empty'],
[(value: string) => value.length < 10, 'String is long'],
);
createValidation
accepts variadic number of [Predicate, string]
tuples and returns a function which accepts value of first predicate’s argument type and when called, checks validators one after another against this value until one of them returns false. In this case, function has to return { ok: false, error: string }
. If all predicated passed, then it returns { ok: true, data: T }
where T
equals to type of last predicate’s argument type.
Also, types of predicates have to be consistent, meaning the following should be a TS error:
const validateString = createValidation(
[(value: unknown): value is string => typeof value === 'string', 'Value is not a string'],
[(value: string) => value.length > 0, 'String can not be empty'],
[(value: string) => value.length < 10, 'String is long'],
[(value: number) => value === 123, 'A number?'], // ERROR since 3rd predicate's arg is of type string
);
I tried to implement the function using variadic tuple types, but had no significant success.
Since, I suppose, some kind of composition is involved here and remembering that it is not trivial thing in TS, my question is is it even possible to achieve such kind of thing?
whysoserious is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.