I am not concerned with installing Typescript in the project like in this post: Adding TypeScript to existing create-react-app app. I ve already done all the installation of Typescript. What really puzzles me is the question, how to add new Typescript files with a .tsx file extension and to get this file type-checked. To be more specific; I just what to add only new files with the .tsx file extension. Unfortunately this doesn t work, because when you import a .tsx file into a file with a .js the .tsx file doesn t get type-check at all. So you have to change the file extension of the existing .js file to .tsx as well. That s were the pain starts, because you have to refactor existing Javascript to Typescript, what I wanted to avoid at all costs. I thought a tweak of the tsconfig.json file would do the trick to leave the Javascript code alone and only type-check code that is explicitly written in Typescript. But to no avail. I counld t figure a way to do it, except painfully refactoring existing code. That`s not a feasible option for my project. This guy in the blog (https://javascript.plainenglish.io/how-to-gradually-adopt-typescript-into-an-existing-express-project-28a0f7a67f2e) explains his strategy: Keep your existing JS code, start writing new code in Typescript. Easier said than done. Does anybody have some insight in that matter? Would be much appreciated!
In general, at least some refactoring will have to happen. I've done this for a MERN stack project, so had to do this for React + NodeJS.
Overall this is what I did:
typescript
) -- shouldn't have any issues.js
to .ts
/ .tsx
-- a bunch of errors should appear depending on the strictness of your tsconfigWhen doing this I ensured to use "strict": true,
in my tsconfig which threw a ton of errors, but also told me what to fix. It is up to you if you prefer that.
To your specific concern:
I just what to add only new files with the .tsx file extension. Unfortunately this doesn t work, because when you import a .tsx file into a file with a .js the .tsx file doesn t get type-check at all. So you have to change the file extension of the existing .js file to .tsx as well.
You should be able to do this, but naturally you wont have type checking in the JS (since its JS). The tsconfig should still highlight / throw errors if there are any inside the .tsx
Overall, I would recommend against having a project that is both JS + TS, it will be tougher to maintain. Rather I would say refactor it now before it grows in size and complexity.
Hope it helped. Good luck!