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

Infers a function signature #861

Closed Rafarel closed 3 weeks ago

Rafarel commented 1 month ago

Since the v.function() has a (...args: unknown[]) => unknown signature, and that valibot infers the type, my code will not accept my function as it is a (arg: string) => string that is expected.

Here is an example of the error I get :

https://valibot.dev/playground/?code=JYWwDg9gTgLgBAKjgQwM5wG5wGZQiOAcg2QBtgAjCGQgbgCh6BjCAO1XgGUmALAUxDI4AXkwA6CBQBWfJjAAUAb3pwcrAFzjsAV1ZzgbeQEoANPQC+RhszYc4UPqm2l4ojGLDIoqPvO79BEzhlVWwNOE4YKGBWAHMzS2sWdngQPhgeCAATETh5JjJSCmQmAGtNeQxNDmi4oxEAPjgamNj64SaQuALSIpLS+UIYRxorC2s0jOz5BycXMTCxm3YIUj4xUghYmcdnGDGgA

What did I miss?

Thanks a lot for this great library!

fabian-hiller commented 1 month ago

Thank you for creating this issue! function does not natively validate its arguments and return type. Therefore, they must be typed as unknown to remain type safe. You can validate and thereby change the type signature as written here, but it may be true that this could be superfluous if you know for sure what the type signature is. Therefore, we should think about allowing users to define the type signature manually.

A quick workaround for now is to use our custom schema instead of function:

import * as v from 'valibot';

const Schema = v.object({
  fn: v.custom<(v: string) => string>((input) => typeof input === 'function'),
});
Rafarel commented 1 month ago

In fact, I have to define an object that will be passed to a library function, so I can't modify the fact that the following code expects this signature without trans-typing.

Thanks a lot for your help it works like a charm

fabian-hiller commented 1 month ago

Did you choose the custom workaround? Do you think we should improve our API to make this easier?