ExodusMovement / schemasafe

A reasonably safe JSON Schema validator with draft-04/06/07/2019-09/2020-12 support.
https://npmjs.com/@exodus/schemasafe
MIT License
155 stars 12 forks source link

fix: relax type on object properties #180

Closed sparten11740 closed 7 months ago

sparten11740 commented 7 months ago

This PR relaxes the type on object properties to accommodate for conflicting type inference as reported in #170

A simplified version of the issue we are facing is the following:

const y = [
  { "X": true },
  { "Y": false }
]

Is inferred as

({
    X: boolean;
    Y?: undefined;
} | {
    Y: boolean;
    X?: undefined;
})[]

properties amongst other is typed as { [id: string]: Schema } . This index signature states that if we have a property, it has to be of type Schema and cannot be undefined. This conflicts with the type that is inferred from e.g. an array provided to allOf, where one element references a different property than the other. Similar to the example above one property in one branch of the union type will then be inferred as propA?: undefined.

A possible solution is to allow keys with undefined values in the index signature using either Partial<{ [id: string]: Schema }> or <{ [id: string]: Schema | undefined }>. The caveat of is that obviously a key with an undefined value does not make sense in properties. Worth paying that price?

This PR does that and adds a test case for the bug from #170

Closes #170

codecov-commenter commented 7 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (f28dd6f) 99.54% compared to head (92bba82) 99.54%.

:exclamation: Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files