71

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?

2
  • as is the recommended syntax for type assertions. I mention this here as well basarat.gitbooks.io/typescript/content/docs/types/… 🌹 Commented Jun 6, 2016 at 1:53
  • This would explain the 100+ errors that resulted in my IDE just from switching the .ts extension to .tsx when porting typescript code into React. There was one <typecast> early on in the file and everything else thereafter was misinterpreted. Commented Jun 14, 2020 at 6:21

1 Answer 1

95

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.