Open MatthiasKunnen opened 3 years ago
I skimmed through it quickly, and I see two major points atm:
_type
parameter this schema is no longer adhered to and the call will fail.I believe we should make our solutions as simple as possible, both for our sake and the user's sake. Ideally, users can understand and implement without reading documentation. To that end we should limit ourselves to the least amount of options required.
The example you mentioned could be implemented as follows:
@jsonObjectInheritance({
resolveType: data => {
const discriminators = {
Cow: Cow,
Dog: Dog,
Cat: Cat,
};
return discriminators[data.type] ?? Animal;
},
})
@jsonObject()
class Animal {
}
I believe this approach would be more readable and easier to understand than adding the feature you described. It does not require more code on our end and does not leave the user thinking about how the resolveType
function and discriminatorMatcher work together. What do you think?
@JohnWeisz, I've appended this PR with discriminatorProperty
which is used like this:
@jsonInheritance(discriminatorProperty({
property: 'type',
types: () => ({
Employee: Employee,
Investor: Investor,
PartTimeEmployee: PartTimeEmployee,
}),
}))
@jsonObject
class Person {
name: string;
}
This functionality enables the following flow: {name: "Bob", type: "PartTimeEmployee"}
gets deserialized into ParTimeEmployee {name: 'bob'}
and this gets serialized back into {name: "Bob", type: "PartTimeEmployee"}
.
Does this approach work for your use case?
I'm currently investigating some issues with circular references and multiple jsonInheritance
decorators. I'll let you know when the PR is ready for review again.
Rebase complete
Implemented in fork @Decoverto
This PR continues on top of #158 by reworking inheritance.
The PR removes
knownTypes
,typeHintEmitter
,typeResolver
, andnameResolver
with a more comprehensive@jsonObjectInheritance
decorator. The new implementation is also a lot less complex. 330 lines of source code get deleted :rocket:.Since this PR is branched from #158, the diff will include changes from that PR. For only the inheritance rework, see: https://github.com/MatthiasKunnen/TypedJSON/compare/issue-139-define-type-lazily...MatthiasKunnen:rework-inheritance.
Todo: