-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Feature request: built in method to get Typescript instances from JSON #7233
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Looking forward for it. |
duplicate of #2064 |
@stunaz Great! That is exactly what is needed. I hope something like this can be integrated into the Typescript library itself. Re: "Since Typescript does not have good reflection abilities yet, we must implicitly specify what type of object each property contain." Could properties created with emitDecoratorMetadata be used for this purpose to avoid new annotations specific to your lib? Minor tweak suggestion: change "Skip" to "NotMapped" (term from Entity Framework code first annotations). |
Providing a runtime library and/or builtin reflection capabilities are out of scope of the typescript project for the time being. |
The capability has been discussed here and here and here. I would like to see a built-in way of doing this in the Typescript language itself. Sort of like a deserializer.
JSON is the language of data. Typescript will have greater adoption if there is an easy way to 'cast' a JSON string (or the javascript object created from it) into an instance of a Typescript class. If it is just the javascript object, it doesn't have methods of the class and items initialized with the constructor.
In the links above, one challenge is complex classes, ie: instance of Car class that has instance of Engine class in the same JSON. There is not an elegant way of doing this. The closest is to adopt a convention for metadata in the JSON which shows the subclass name. For example, a property like name = "Engine", so the 'deserializer' knows what type of class to instantiate for the subclass items. One suggestion to make the convention less arbitrary would be to use metadata that Typescript adds to the javascript when using Typescript's reflection. If that was the approach, it would probably make sense to also create a 'serializer' that when stringifying the Typescript instance, also included the necessary metadata.
Could there be a way to accomplish this with Typescript declaration merging or mixins?
The text was updated successfully, but these errors were encountered: