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();

Using the preceding cast, you have full support and recognition by TypeScript that products is now an array of objects with a name key.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.115.155