Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript or JavaScript type casting

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?

like image 465
Klaus Nji Avatar asked Nov 03 '12 00:11

Klaus Nji


People also ask

Is type casting bad in TypeScript?

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.

Does JavaScript support type casting?

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().

How do I cast objects in TypeScript?

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.

Does python have type casting?

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.


1 Answers

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.

like image 75
blorkfish Avatar answered Oct 02 '22 21:10

blorkfish