Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a TypeScript cast with JSX/TSX

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?

like image 608
RationalDev likes GoFundMonica Avatar asked Jun 03 '16 12:06

RationalDev likes GoFundMonica


People also ask

How do you do a cast in TypeScript?

JavaScript doesn't have a concept of type casting because variables have dynamic types. However, every variable in TypeScript has a type. Type castings allow you to convert a variable from one type to another. In TypeScript, you can use the as keyword or <> operator for type castings.

Can I use JSX in TSX?

JS, JSX, or TSX? @NickSmith React is smart enough to understand React components inside a JS file even though it's not valid JavaScript. You can use both JS and JSX extension to use a React component. As far as what is used more commonly, it's a matter of choice.

Can I use TypeScript in JSX?

TypeScript supports embedding, type checking, and compiling JSX directly to JavaScript.

How do I convert TSX to JSX?

If just running tsc doesn't work, read this code.visualstudio.com/docs/typescript/typescript-compiling Effectively you can just compile it into Javascript. If the output of tsc is too much, just go through the tsx files and remove TS specific syntax, then rename to . jsx.


1 Answers

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)

like image 109
RationalDev likes GoFundMonica Avatar answered Sep 21 '22 13:09

RationalDev likes GoFundMonica