What is the reason behind TypeScript not incorporating Type Casting and only focusing on Type Assertion? I'm not seeking a solution for my code, but rather an explanation as to why Type Casting is omitted in TypeScript, and why it is advised against implementing it independently.
For instance, imagine having a TypeScript front-end that receives JSON data from the backend through AJAX calls, with multiple nested elements. Let's say it pertains to food, where the price is determined based on the current hour.
Consider the following JSON:
{
"food" : [{
"name" : "pizza",
"price" : 1.234
"ingredients" : [
"name" : "cheese",
"extra_price" : 1.2345
]
}
]
}
Now, let's introduce these classes:
class Food {
public name : string;
public price : number;
public ingredients : Ingredient[];
public timePrice() : number {
return this.price * (new Date()).getHours();
}
}
class Ingredient {
public name : string;
public extra_price : number;
}
If we attempt to Cast these types in TypeScript, we can access the properties seamlessly, even those within ingredients. However, we encounter a limitation when trying to utilize the timePrice function due to TypeScript utilizing Type Assertion instead of Type Casting.
While one workaround could involve creating a constructor that instantiates the class when passing properties as parameters, this method becomes impractical when dealing with multiple nested elements. In such cases, creating a Utils class with static functions and using Food and Ingredient as parameters proves to be effective.
But why hasn't Type Casting been implemented in TypeScript? Although it may seem achievable, the fact that Microsoft has not included it implies there are potentially significant challenges associated with its implementation.