Repository navigation
Validate function return type #780
Replies: 2 comments
|
Have a look at #243 (comment). import * as v from 'valibot';
// Simple but less readable version
const Schema1 = v.pipe(
v.function(),
v.transform((func) => () => v.parse(v.promise(), func()))
);
// Longer and more readable version
const Schema2 = v.pipe(
v.function(),
v.transform((func) => {
return () => {
const result = func();
const parsed = v.parse(v.promise(), result);
return parsed;
};
})
);And if your function have import * as v from 'valibot';
// Simple but less readable version
const Schema1 = v.pipe(
v.function(),
v.transform(
(func) =>
(...args: unknown[]) =>
v.parse(v.promise(), func(...args))
)
);
// Longer and more readable version
const Schema2 = v.pipe(
v.function(),
v.transform((func) => {
return (...args: unknown[]) => {
const result = func(...args);
const parsed = v.parse(v.promise(), result);
return parsed;
};
})
); |
|
For current Valibot, there is a built-in option for checking that the function completes with import * as v from 'valibot';
const Schema = v.pipe(v.function(), v.returnsAsync(v.void()));
const checked = v.parse(Schema, async () => {});
await checked(); // resolves to undefined
const wrong = v.parse(Schema, async () => 123);
await wrong(); // rejects with ValiErrorUse the wrapped function returned by This also addresses a distinction in the earlier One caveat: this is not an exact “must return a Promise” check. In Valibot 1.5.0, I checked this with Valibot 1.5.0 and TypeScript 5.9.3 in strict mode: the wrapped output is Reference: |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Is it possible to validate a functions return type using Valibot?
To be more specific, I am trying to replace my Zod implementation
z.function().returns(z.void().promise())with something like
v.pipe(v.function(), v.returns(v.void().promise()))Zod docs from original use: https://zod.dev/?id=functions
Valibot docs for
functions: https://valibot.dev/api/function/All reactions