adding SemiPartialType and associated tests#654
adding SemiPartialType and associated tests#654mjburghoffer wants to merge 3 commits intogcanti:masterfrom
Conversation
|
I actually quite like SemiPartial as a name. I'm less keen on the proposed API though - personally I think something like the following looks and feels a little nicer to use: t.semiPartial({
requiredField: t.required(t.string),
optionalField: t.optional(t.string),
});I think the part that I dislike about your API is that optional and required fields are specified in quite different ways. This is great work - it's about time someone decided to tackle this long standing issue, and regardless of the API I think it will be much nicer to use than the current intersection solution. |
|
Just in case anybody in the future stumbles across this, I had a play around with this branch and fixed a few issues, specifically:
My (possibly buggy!) changes are here: https://github.com/mwilliamson/io-ts/tree/semi-partial I think I'll probably ending up taking a different approach, but this branch was definitely useful as inspiration! |
Since having a struct with a mix of required and optional properties is so common, I figured it would be nice (and more performant) to have a purpose-built type. I know you could achieve similar by doing
intersection(type(...), partial(...)), but this approach feels more readable and easy to refactor.To address the elephant in the room: I am aware that
SemiPartialis not a great name - so maybe renaming the type is in order :)It is worth noting that the method signature for
semiPartialis 100% backwards compatible withtype-- therefore, it would be an option to simply replacetypewith this code, and simply extend its capabilities.It has been requested before: #450
There is another old but still active PoC pull request: #266
And it has been asked on stackoverflow a number of times (some of many examples below):
https://stackoverflow.com/questions/48230773/how-to-create-a-partial-like-that-requires-a-single-property-to-be-set
https://stackoverflow.com/questions/61311182/a-partly-partial-with-io-ts
In addition to the new functionality, the behavior of
TypeOfis exactly as you would define an interface. In other words the typechecker will treat the two following examples identically: