Why did TypeScript not implement Type Casting but only Type Assertion? I'm not looking for an answer for my code, but for the reason that Type Casting is not implemented in TypeScript, and why we not should (assumption!) implement it at our own.
Example. I've an TypeScript front-end, receiving JSON-data from the backend via AJAX-calls, having elements in elements in elements. It's about food, and you have to pay the price multiplied by the hour of the day.
We got this JSON:
{
"food" : [{
"name" : "pizza",
"price" : 1.234
"ingredients" : [
"name" : "cheese",
"extra_price" : 1.2345
]
}
]
}
And we have 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 Cast this types using TypeScript, we can perfectly use the properties, including the ingredients. Perfectly.
But: We can't use the function timePrice. Because TypeScript does Type Assertion and NOT Type Casting.
I'm aware of the option that you could write a constructor creating the class when you pass the properties as parameters, but if you have elements in elements in elements: not an option. So the only option to fix this for me is to create a Utils class with static function and Food and Ingredient as parameters. That's working.
But why? What is the problem with Type Casting that it isn't implemented in TypeScript? It seems not so hard to me to build it, but because MicroSoft did not do this, there must be insurmountable problems by doing this.