Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ts for tsx react files

Is it possible to use .ts extensions for React typescript .tsx files without the IDE and the compiler going crazy?

like image 247
Kousha Avatar asked Dec 23 '16 18:12

Kousha


People also ask

Can I use ts instead of TSX?

tsx extension is used when we want to embed JSX elements inside the files while . ts is used for plain Typescript files and do not support adding JSX Elements.

Can we use ts file in React?

TypeScript is a language which extends JavaScript by adding type definitions, much like Flow. While React Native is built in Flow, it supports both TypeScript and Flow by default.

What is a TSX file TypeScript?

A TSX file is a TypeScript (. TS) file written using JSX syntax. It contains code that is most likely part of a single-page or mobile application. TSX files can be opened in any text editor, but are meant to be opened in source code editors.


1 Answers

Right now, no. There are technical reasons for the existence of the .tsx extension.

There is an ambiguity that JSX introduces when it comes to TypeScript's original type assertion syntax - specifically, it's not clear if <Foo>xyz is the start of a JSX tag or a type assertion. That's why we had to adopt the as type assertion syntax (i.e. xyz as Foo) and introduce the .tsx file extension.

Even aside from that, supporting JSX means that TypeScript has to decide on how to disambiguate something like a generic arrow function. For example, in this case

let identity = <T>(x: T) => x

TypeScript parses that as the start of a JSX tag. Users have to turn this into a non-ambiguous form to get the equivalent code:

let identity = <T extends {}>(x: T) => x

In short: supporting JSX would have implied breaking changes or a whole lot of unnecessary complexity in the compiler with worse error recovery for JSX.

like image 181
Daniel Rosenwasser Avatar answered Sep 21 '22 04:09

Daniel Rosenwasser