How does one handle type casting in TypeScript or Javascript?
Say I have the following TypeScript code:
module Symbology { export class SymbolFactory { createStyle( symbolInfo : SymbolInfo) : any { if (symbolInfo == null) { return null; } if (symbolInfo.symbolShapeType === "marker") { // how to cast to MarkerSymbolInfo return this.createMarkerStyle((MarkerSymbolInfo) symbolInfo); } } createMarkerStyle(markerSymbol : MarkerSymbolInfo ): any { throw "createMarkerStyle not implemented"; } } }
where SymbolInfo
is a base class. How do I handle typecasting from SymbolInfo
to MarkerSymbolInfo
in TypeScript or Javascript?
Typescript is about typings, but you always have a way to break the typing for good or bad reasons. So here are some key advices. Always type (not cast) all your code but forget the any as much as possible. If you have to cast, it's a polymorphism-like reason, or it's probably a code smell.
Type casting means conversion of one data type to another explicitly. In JavaScript some of the most common methods to convert a datatype to either string using String(), to boolean using Boolean(), or to number using Number().
If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.
Python avoids the loss of data in Implicit Type Conversion. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With