Kousha
Kousha

Reputation: 36189

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?

Upvotes: 7

Views: 8057

Answers (2)

Pengő Dzsó
Pengő Dzsó

Reputation: 865

With Babel you can use this switch:

https://babeljs.io/docs/en/babel-preset-typescript#istsx

we should use the new type assertion syntax everywhere anyway...

Upvotes: 1

Daniel Rosenwasser
Daniel Rosenwasser

Reputation: 23443

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.

Upvotes: 10

Related Questions