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!
-
3Possible duplicate of stackoverflow.com/questions/34224007/…– user47589Jul 3, 2019 at 13:34
-
Roughly I use .ts files for plain scripts and .tsx for files containg markup– MangsJul 3, 2019 at 13:38
-
same as difference between c and c++ :p– Ubiquitous DevelopersJul 3, 2019 at 13:53
-
Does this answer your question? Is there any downside to using .tsx instead of .ts all the times in typescript?– GorvGoylJun 17, 2020 at 0:12
5 Answers
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
.
-
11To add to this (correct) answer, it's the same as if you were doing React without TypeScript, you would use .js and .jsx for pure javascript vs JSX javascript files. Jul 3, 2019 at 13:50
-
not necessarily, you can write pure TS React components, I'd reword it as: a react component containing "tag like" react syntax (which is really tsx). Just to clarify that to anyone that doesn't really know about it.– sabOct 14, 2020 at 7:54
-
5
-
5I spent many hours figuring out why my .ts files keep throwing errors for things like
return <div>hello!</div>;
. Kill me please. Mar 20, 2022 at 12:10 -
what about hook files that doesnt contain react component? like maybe a react spring custom hooks is it useAnimation.ts or useAnimation.tsx? Apr 18, 2022 at 6:53
.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.
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.
-
Hint: If you use <> to do type-casting in your .ts file and you paste that into a .tsx file, then that will lead to errors. Replace all <typeA> myVar with myVar as typeA and you're good to go. Jul 28, 2022 at 12:30
when you use .tsx you can use JSX in that particular file while .ts gives you error.