sindresorhus / ow

Function argument validation for humans
https://sindresorhus.com/ow/
MIT License
3.8k stars 105 forks source link

generate objects from predicate #229

Open DuredhelFinceleb opened 2 years ago

DuredhelFinceleb commented 2 years ago

Hi !

Let's say I have objects representing a DB record and I wrote this to validate them

const myRecordType = ow.object.exactShape({
  id: ow.string,
  axis: ow.string.oneOf(['X', 'Y', 'Z']),
  value: number,
  name: ow.optional.string,
});

How can I use this to generate new empty records? The idea would be to create a function that returns a correctly initialized object

const newRec = generateNewRecord(myRecordType);
console.dir(newRec);
/*
{
  id: '',
  axis: 'X',
  value: 0,
  name: '',
}
*/
DuredhelFinceleb commented 2 years ago

I should add that I'm asking this in the context of a JavaScript codebase that won't migrate to TypeScript anytime soon Using ow is my attempt to bring in some type sanity and stop wasting my brain as a type-checker

sindresorhus commented 2 years ago

I think that's a bit out of scope for this package. Ow is meant for validation only.


Also, it's ambiguous in many cases which would be the correct value to return.

axis: ow.string.oneOf(['X', 'Y', 'Z']),

A user might be fine with the first value there, but they also might want to specify a custom default. It's a slippery slope for API bloat.

DuredhelFinceleb commented 2 years ago

Yes it's ambigiguous and precisely the reason why I put it in my example 🙂

That being said, I did not meant for 'ow' to provide something like this. I wanted to know if it is possible to build a function for my project which would allow me to construct an object from its definition. I guess I could test the type of the predicate for each property and set my default value accordingly. Then again for things like 'axis', I'm not sure how I would programatically get the info that only 'X', 'Y' or 'Z' are accepted.

I know that 'ow' is for validation only, but I'm not on the TypeScript train with this code base, so when you're stuck with JavaScript, 'ow' is the closest thing I've found so far to have some type system that actually works & is easy to use (and if you know of a more appropriate project for this than 'ow', I'm all ears 😀 )