Skip to content

TypeScript assertion function #862

@gcornut

Description

@gcornut

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 ?

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestpriorityThis has priority

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions