212

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!

4

5 Answers 5

316

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.

5
  • 11
    To 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.
    – Cal Irvine
    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.
    – sab
    Oct 14, 2020 at 7:54
  • 5
    flawless answer!
    – Gaurav
    May 6, 2021 at 20:38
  • 5
    I 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?
    – kafinsalim
    Apr 18, 2022 at 6:53
49

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

21

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.

1
  • 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
7

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

0

.ts is used for pure TypeScript files and .tsx is used for files with JSX.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.