TypeScript or JavaScript type casting
Asked Answered
S

3

286

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?

Shute answered 3/11, 2012 at 0:17 Comment(0)
S
415

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.

Spinous answered 3/11, 2012 at 5:53 Comment(4)
Now, I see that in in doc, referred to as Type Assertions in section 4.13.Shute
This answer does no longer provide the full picture of type assertion in typescript, whereas Alex's answer gives a more complete picture, and should be the accepted answer.Sachikosachs
@KristofferDorph This answer is 4 years old. At the time of writing TypeScript was at version 0.8.1, and thus was the correct answer at the time. JSX support was only included 3 years later.Spinous
@Spinous that is true, but it is good practice to follow the times, so people asking the same question today gets the current answer, and not as it where 4 years ago :-)Sachikosachs
C
247

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.

Carbamate answered 12/2, 2016 at 12:10 Comment(4)
How do you indicate to typescript that you have converted an object to another type? For example a func that returns type2, inside it it http gets type 1, does logic to convert, and returns what was type1 but is now type2?Ity
@TonyGutierrez How do you do the conversion?Carbamate
Basically take one property and modify. The only way I have found to do this is to create a new var (type2) and copy in the props from the type1var and then return it. You can't modify the type1 and return, or you get a "Can't cast" error.Ity
"the original syntax conflicted with JSX" - I think "conflicts" would be a better wording, since the conflict is still there with the original syntax.Quality
M
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

Moonier answered 13/7, 2020 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.