ianstormtaylor / superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
https://docs.superstructjs.org
MIT License
6.96k stars 223 forks source link

Feature Request: Infer the other way. #1159

Open ivands opened 1 year ago

ivands commented 1 year ago

The Infer function is great because it allows us to get the output types of a given struct. However, it would also be great to be able to get the input types of a given struct. I'll give an example of the difference:

The following struct will always output a number.

const MyNumber = coerce(number(), string(), (value) => parseFloat(value))
type OutputType = number // generated by Infer

However, it can accept numbers & strings. So the input type would be:

type InputType = string | number

I need a way to Infer the input type of a struct. Also, I think this would be a great addition to the already great lib.

ianstormtaylor commented 1 year ago

Very cool idea, I'd be open to a pull request that implements this! Feel free to talk through the implementation here too to see if it will work or what the gotchas might be.

ivands commented 1 year ago

Sadly I'm just learning typescript, so I'm not sure if I can be much help atm. (This might change in the future XD) However, I do know Zod already has a way to infer the input type of a given struct. Maybe we can learn something from their implementation. Superstruct still has a superior API tho, because of its tree-shakeablitity, making it ideal for serverless functions.

ziad-saab commented 1 year ago

@ianstormtaylor I took a stab at this here: https://github.com/ianstormtaylor/superstruct/pull/1181

It's probably not mergeable as-is, but lmk what you think.

ivands commented 1 year ago

Cool work @ziad-saab 👍. I hope it can be merged soon because we really need this feature at the moment.

@ianstormtaylor What do you think?

hmalik88 commented 1 year ago

Bump, would like this change to be added in. Have you had a change to look? @ianstormtaylor