Imagine needing to process JSON responses where all parameters are encoded as strings, regardless of their actual type. The goal is to strictly typecast these values into various Typescript classes. For example, consider the following JSON:
{"id":"1","label":"Alice"}
Now, let's say we have a Typescript class defined as follows:
class Person {
public id:number;
public label:string;
}
In other programming languages like AS3, it is possible to directly assign values without explicit type conversions, as shown below:
var p:Person = new Person();
p.id=jsonInput.id;
p.label=jsonInput.label;
However, in my particular case, I frequently encounter complex JSON objects that require dynamic creation, updates, and destruction of Typescript objects based on server data. It can be cumbersome to manually check if each parameter is numeric before assigning values. Even though a class property is declared as a specific type, such as number, at runtime it may still accept a string assignment without any validation.
This issue becomes especially troublesome when dealing with boolean values represented as "0" or "1" strings from the server. Forced comparisons with these strings are necessary, leading to inefficiencies.
Therefore, I am seeking an elegant solution to enforce type constraints specified in the class definition during property assignments. Rather than constantly checking for data types received from the server, I aim to utilize the class definition to automatically cast values appropriately. For instance, receiving a non-numeric string should result in either null or an error if assigned to a number property; assigning a number to a string property should yield a string value instead of throwing an error. Similar behavior is expected for boolean properties. Is there a way to achieve this level of type safety in Typescript as seen in other languages?