Recently I've been adding an assert utility function in my projects that is simply the Valibot parse function wrapped and types as a TypeScript assertion function.
export function assert<TSchema extends v.GenericSchema>(
schema: TSchema,
value: unknown,
config?: v.Config<v.InferIssue<TSchema>> | undefined,
): asserts value is v.InferInput<TSchema> {
v.parse(schema, value, config);
}
function main(something: unknown) {
assert(v.string(), something, { message: 'Can only lower case a string' });
return something.toLowerCase();
}
console.log(main(4));
Hello,
Recently I've been adding an
assert
utility function in my projects that is simply the Valibot parse function wrapped and types as a TypeScript assertion function.(in the playground)
It's pretty useful to do type narrowing with abort and the Valibot error messages. Maybe this method could be used in the Valibot library ?