How to use a TypeScript cast with JSX/TSX

TypescriptReact Jsx

Typescript Problem Overview


When casting in a .tsx file, the compiler assumes it to be JSX, e.g.:

(<HtmlInputElement> event.target).value

gives an error

> JSX element type 'HtmlInputElement' is not a constructor function for JSX elements

How do you cast TypeScript in a .tsx file?

Typescript Solutions


Solution 1 - Typescript

The as operator was introduced to TypeScript 1.6 to replace casts in .tsx files, e.g.:

(event.target as HTMLInputElement).value

The TypeScript wiki explains the 1.6 changes: it makes the new as operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRationalDev likes GoFundMonicaView Question on Stackoverflow
Solution 1 - TypescriptRationalDev likes GoFundMonicaView Answer on Stackoverflow