appvision-gmbh / json2typescript

Map JSON to a TypeScript class with secure type checking!
https://www.npmjs.com/package/json2typescript
MIT License
278 stars 55 forks source link

Improve discriminator #181

Closed andreas-aeschlimann closed 2 years ago

andreas-aeschlimann commented 2 years ago

As discussed in https://github.com/appvision-gmbh/json2typescript/pull/165, we should test and merge this PR before releasing v1.5.0.

Closes https://github.com/appvision-gmbh/json2typescript/issues/168 Closes https://github.com/appvision-gmbh/json2typescript/issues/169 Closes https://github.com/appvision-gmbh/json2typescript/issues/171

andreas-aeschlimann commented 2 years ago

Hey @Catter38, I fixed the error that appeared in your tests.

The problem was that you expected the code to work when

From your implementation, I think you want the code to throw an error in this case, even if the user provides a type in the deserialize method. Of course the code could fall back to the given type in the deserialize property, but I think this should not be done to avoid bugs in projects. A developer should decide to either use the discriminator feature and when the $type is given in the json, it will force you to register the classes.

That said, I also implemented a lazy-loading feature which is kinda neat to fix circular dependencies. If you want, take a look at the ReadMe https://github.com/appvision-gmbh/json2typescript/blob/ab4a974ff06a95af3b7f399a5d8cc1a0ff8b04f9/README.md, at the chapter "Instantiation with the lazy-loading feature to avoid circular dependencies".