Type casting

The TypeScript type system allows us to cast a given type using two different syntaxes:

var myObject: TypeA;var otherObject: any;myObject = <TypeA> otherObject; // Using <>myObject = otherObject as TypeA; // Using as keyword

It is important to understand that the TypeScript casting does not affect the runtime type of the variables.

Since Typescript 1.6, the default is as, because <> is ambiguous in .tsx files. We will learn more about .tsx files in Chapter 11, Frontend Development with React and TypeScript.

In general, it is recommended to avoid using type castings and prefer generic types instead.

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.