Search code examples
javascripttypescript

Can I use ts files the exactly same way I use js files?


I've heard about TypeScript and I liked it, because I've always liked making annotations in my code. However, I would have to rename all my .js files to .ts files. I would like to add annotations to my functions with all TypeScript capabilities without renaming my files. But, as I learned later, that is not possible. So, my question is: Can I continue typing JavaScript code normally after renaming them to .ts extension?

I have already added some annotations like

@param{string} argumentExplanation

and this is helping very much. However, I would like to do more than this to help on my code. The reason is that the code annotations will help me to create a future documentation about my project.


Solution

  • When using Typescript, a local TS server is attached to the compliation process and checks the written code against the annotations to spot possible errors at compliation time.

    Simply renaming you files won't enable typescript, there is a configuration process to follow https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

    If your project was manually created or doesnt have a compliation process (eg: webpack, vite/rollup) you've got a bit of work to do following the guides in the link provided above.

    If you bootstrapped the project with something like CRA (Create React App) then I highly recommend rebootstrapping the App for typescript using the vendor tools usually located on the repository or their main documentation website, and copying your existing code in (which sounds daunting but is actually a quick copy paste vs a deep dive into the required configurations).

    Alternatively if you're learning an find the concepts overwhelming you could look into JsDoc which provides some type annotation assistance without having to rejig your entire project. https://jsdoc.app/

    Ultimately TypeScript will make you a better programmer who makes less mistakes so it is worth diving into.