gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

optional `getTcombFormOptions` function on types #376

Closed gcanti closed 7 years ago

eteeselink commented 7 years ago

Wow, that simple huh? :-)

I agree that it's better with the function, in case people want to mix and match options intelligently. I can't come up with a concrete use case for that right now but it appears to be the more dynamic approach nevertheless.

I did a little code review and it looks good to me.

gcanti commented 7 years ago

Ok, I'll publish this feature (tagged as experimental) asap so you can make some assessments on your codebase

gcanti commented 7 years ago

@eteeselink released in https://github.com/gcanti/tcomb-form/releases/tag/v0.9.11

eteeselink commented 7 years ago

Wow, that's fast! :-) Thanks!!

Ok, I refactored our large nested tcomb form to this and it's pretty fantastic. The code is a lot easier to follow. I didn't find a use for the options parameter, so all my code looks like this

SomeType.getTcombFormOptions = () => ({
    ...
});

but that's fine. I guess the dynamism is really neat when amending forms from external libs that are somehow difficult to modify (open source, different team, whatever).

Another thing I noticed this did to my code: I started making named types for simple things had the same type but different semantic. Before getTcombFormOptions I had, for instance, a type like this:

const SuppressContactInfo = t.struct({
    allowedHostnames: t.maybe(t.list(t.String)),
    allowedPhoneNrs: t.maybe(t.list(t.String)),
    allowedMatches: t.maybe(t.list(Regexp))
}, "SuppressContactInfo");

After refactoring the code, I found myself extracting the types for allowedHostnames and friends into separate named type objects:

const AllowedHostnames = t.maybe(t.list(t.String));
AllowedHostnames.getTcombFormOptions = () => ({
    ...
});

This way, I avoided having a still-quite-deeply-nested options object on SuppressContactInfo, and the help text and stuff like that was very close to the actual field. I like this because it means that getTcombFormOptions encourages me to make my code better - named types for nontrivial things are probably often a good idea.

The file when from deepest indent starting at column 33 to column 12.

Sharing all this just because I suspect you're interested. :-) Shall I add it to the GUIDE.md?

gcanti commented 7 years ago

Sure! If you are willing to add some documentation / examples for this new feature, it would be great. I'l gladly accept a PR