I just start working on a React project with TypeScript and ask myself what should I do with regular class files? Should I use .ts
or .tsx
files an
The reason why .jsx extension was introduced is that JSX is an extension of JS syntax and thus .jsx files don't contain valid JavaScript.
TypeScript follows the same convention by introducing .ts and .tsx extensions. A practical difference is that .tsx don't allow
type assertions because the syntax is in conflict with JSX tags. as Type
assertions was introduced as a replacement for
and considered a preferred choice for consistency reasons in both .ts and .tsx. In case the code from .ts is used in .tsx file,
will need to be fixed.
The use of .tsx extension implies that a module is related to React and uses JSX syntax. In case it doesn't, the extension may give false impression about module contents and the role in the project, this is the argument against using .tsx extension by default.
On the other hand, if a file is related to React and has good chances to contain JSX at some point, it can be named as .tsx from the beginning to avoid renaming later.
For instance, utility functions that are used together with React components may involve JSX at any point and thus can be safely use .tsx names, while Redux code structure isn't supposed to use React components directly, can be used and tested apart from React and can use .ts names.