What is the difference between .ts and .tsx extensions. Both are used as extensions for typescript files in react. So where should we use them?

ReactjsTypescript

Reactjs Problem Overview


I am new to react and I am working on a project. I come across both .ts and .tsx extensions. I don't understand where should I use .ts and .tsx. Any help on this is much appreciated. Thank you!

Reactjs Solutions


Solution 1 - Reactjs

Use .ts for pure TypeScript files.

Use .tsx for files which contain JSX.

For example, a React component would be .tsx, but a file containing helper functions would be .ts.

Solution 2 - Reactjs

.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.

Solution 3 - Reactjs

All of the above answers are correct.

> .ts files contains only pure TypeScript

> .tsx have included JSX also.

On another point of view, you can copy everything from a .ts file and paste on .tsx file, and you don't need to modify anything. But if you're copying from a .tsx file you need to refactor it by removing the JSX elements.

Solution 4 - Reactjs

when you use .tsx you can use JSX in that particular file while .ts gives you error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHafsa MushtaqView Question on Stackoverflow
Solution 1 - ReactjsliamgbsView Answer on Stackoverflow
Solution 2 - ReactjsSachinView Answer on Stackoverflow
Solution 3 - ReactjsManoj PerumarathView Answer on Stackoverflow
Solution 4 - ReactjsRahulView Answer on Stackoverflow