patterntypescriptCritical
TypeScript or JavaScript type casting
Viewed 0 times
typescripttypecastingjavascript
Problem
How does one handle type casting in TypeScript or Javascript?
Say I have the following TypeScript code:
where
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?Solution
You can cast like this:
Or like this if you want to be compatible with tsx mode:
Just remember that this is a compile-time cast, and not a runtime cast.
return this.createMarkerStyle( 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.
Code Snippets
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);Context
Stack Overflow Q#13204759, score: 418
Revisions (0)
No revisions yet.