fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
6.33k stars 204 forks source link

TypeScript assertion function #862

Closed gcornut closed 1 month ago

gcornut commented 1 month ago

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.

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));

(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 ?

fabian-hiller commented 1 month ago

Sorry for the late reply. I will try to have a look and give you feedback in the next few days.

fabian-hiller commented 1 month ago

Great idea! Will implement it!

fabian-hiller commented 1 month ago

v1.0.0-beta.1 with the assert method is available