Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

generate objects from predicate #229

Open
DuredhelFinceleb opened this issue Jan 11, 2022 · 3 comments
Open

generate objects from predicate #229

DuredhelFinceleb opened this issue Jan 11, 2022 · 3 comments

Comments

@DuredhelFinceleb
Copy link

DuredhelFinceleb commented Jan 11, 2022

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
Copy link
Author

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
Copy link
Owner

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
Copy link
Author

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 😀 )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants