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?

3 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.

4

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo; // Newer additional syntax var markerSymbolInfo = symbolInfo as MarkerSymbolInfo; 

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicts with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

4

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) { // access .marker here const marker = symbolInfo.marker } 

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy