paldepind / union-type

A small JavaScript library for defining and using union types.
MIT License
478 stars 28 forks source link

Partially-applied type constructors as validator functions? #35

Open kwijibo opened 8 years ago

kwijibo commented 8 years ago

I wanted a way to define that particular types of Fieldset should have a particular set of fields, and came up with this:

const Type = require("union-type")
const Input = Type({Text: [String, String]}) //fieldname, value
const Fieldset = Type({Contact: [Input.Text('Name'), Input.Text('Work Email')]})
const c = Fieldset.Contact(Input.Text('Name', 'Ted'), Input.Text('Work Email', 'ted@example.net'))

Hoping that since Types double as constructors and validator functions, that a partially applied Type could work as a validator that required the partially applied values. But obviously they don't.

Was that a crazy thing to hope for? Is there a better way to solve my problem?

paldepind commented 8 years ago

This should work.

const Type = require("union-type")
const Input = Type({Text: [String, String]}) //fieldname, value
const Fieldset = Type({Contact: [Input.Text, Input.Text]})
const c = Fieldset.Contact(Input.Text('Name', 'Ted'), Input.Text('Work Email', 'ted@example.net'))

But if Fieldset should always have the labels "Name" and "Work Email" then I don't think it makes sense to include them. They're constants. You might do this:

const Type = require("union-type")
const Fieldset = Type({Contact: [String, String]})
const c = Fieldset.Contact('Ted', 'ted@example.net')

If fieldsets can have different labels in other cases you could do this:

const Type = require("union-type")
const Input = Type({Text: [String, String]}) //fieldname, value
const Fieldset = Type({FieldPair: [Input.Text, Input.Text]})
const ConcatFieldset = (name, email) =>
  Fieldset.FieldPair(Input.Text('Name', name), Input.Text('Work Email', email))