Using Casting in TypeScript
Down Casting in TypeScript
TypeScript includes the ability to cast types. In order to cast a type in TypeScript you use the <> brackets with the relevant type to cast. In order to show how you can use casting lets take the Greeter example that is included in TypeScript website:
In the Greeter class we expect a span which is of type HTMLElement. TypeScript includes a type called HTMLSpanElement which extends the HTMLElement type. So if we change the declaration of the span field to
you will get syntax error in the following constructor line:
The error occurs because the document.createElement function returns a HTMLElement and not a HTMLSpanElement. In order to fix the problem, you will need to use the casting in that line of code:
The <HTMLSpanElement> will tell the TypeScript compiler to cast the HTMLElement returned from document.createElement function into HTMLSpanElement. That will fix the syntax error.
Up Casting in TypeScript
As opposed to the previous down cast example, the option to up cast a type is straight forward in TypeScript. For example, the following code is valid:
TypeScript includes the ability to down and to up cast types. You use the <> brackets in order to down cast a type. In up casting, you just need to know that one type is a subclass of another type.