What is the type assertion operator for TypeScript?

The specification does not say where a type statement can be useful in TypeScript. I do not need this in my code. Therefore, I am curious what problems he must solve. Any ideas?

+6
source share
2 answers

This is a bit like type casting , since it does not come with runtime support (only its compilation time statement) TypeScript allows you to call it โ€œStatement Typeโ€. Consider this example:

 var element1 = document.getElementById('canvas'); // Determined to be HTMLElement element1.getContext('2d'); // ERROR as it is HTMLElement // Determined to be canvas due to your assertion var element2 = <HTMLCanvasElement>document.getElementById('canvas'); element2.getContext('2d'); // Valid 

You will need it whenever the output of TypeScript type leads to the fact that you cannot assign things due to incompatible supposed types.

+14
source

I assume that you mean the notation : [type] after function parameters? This does not seem to affect the final .js file, but if you run the .ts file through the compiler, it will throw an error if it finds an unexpected input type for any valid type parameters. Hope that answers your question.

0
source

Source: https://habr.com/ru/post/956299/


All Articles