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?
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.
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.
TypeScript supports embedding, type checking, and compiling JSX directly to JavaScript.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With