Using Casting in TypeScript
One of the things that are very common in Object-Oriented languages is type casting. In JavaScript, which is a dynamic language, you don’t have the concept of casting. On the other hand, TypeScript language, which compiles into JavaScript, does include casting. This post explains how to use 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:
class Greeter {
element: HTMLElement;
span: HTMLElement;
timerToken: number;
constructor (element: HTMLElement) {
this.element = element;
this.element.innerText += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
start() {
this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
}
stop() {
clearTimeout(this.timerToken);
}
}
window.onload = () => {
var el = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
};In the Greeter class we expect a span which is of type HTMLElement. TypeScript includes a type called HTMLSpanElement which is extends the HTMLElement type. So if we change the declaration of the span field to
span: HTMLSpanElement;
you will get syntax error in the following constructor line:
this.span = document.createElement('span');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:
this.span = <HTMLSpanElement>document.createElement('span');The <HTMLSpanElement> will tell the TypeScript compiler to cast the HTMLElement returned from document.createElement function into HTMLSpanElement. That will fix the syntax error.
Pay attention that the generated JavaScript will look the same for both of the options (the not modified and the modified Greeter examples) and this is because of the dynamic nature of JavaScript.
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:
var el: HTMLElement; el = new HTMLSpanElement();
Since HTMLSpanElement extends the HTMLElement type it is possible to set a HTMLSpanElement instead of HTMLElement.The generated JavaScript for the previous code will be:
var el; el = new HTMLSpanElement();
Summary
TypeScript includes the ability to down cast and to up cast types. You use the <> brackets in order to down cast a type. In up cast, you just need to know that one type is a subclass of another type.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





