Type casting

Having the code statically typed leads to type safety. TypeScript does not let you perform actions that are not considered safe and supported.

In the following example, the loadProducts function is defined with a return value of type any, thus the type of products is inferred as any:

function loadProducts(): any {    return [{name: 'Book1'}, {name: 'Book2'}];}const products = loadProducts(); // products is of type 'any'

In some cases, you may actually know the expected type. You can instruct TypeScript of the type by using a cast. Typecasting in TypeScript is supported by using the as an operator or the use of angle brackets, as follows:

const products = loadProducts() as {name: string}[];const products = <{name: string}[]>loadProducts(); ...

Get Hands-On Full-Stack Web Development with ASP.NET Core 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.