How to fix "type annotations can only be used in typescript files"?
Sometimes when developing a JavaScript/TypeScript project, you might get the "type annotations can only be used in typescript files" error. But what does it mean, and how to fix it?
This article explains everything about this error and shows multiple solutions for it.
Let's get to it 😎.
The error
The "type annotations can only be used in typescript files" error happens when a developer uses TypeScript types in a JavaScript file.
If removing all the TypeScript type annotations from the JavaScript file isn't an option for you, here are some other solutions to fix this error.
Solution #1 - Changing the file extension
The easiest solution to fixing this error is to change the extension of the JavaScript file that outputs this error to a .ts file.
For a React file, you need to change its extension to .tsx.
However, sometimes, changing the file extension might not be possible. For example, you might want to adopt TypeScript incrementally in a legacy project. That is when you can use the next solution.
Solution #2 - Change your VSCode settings
Another solution to this error involves turning off JavaScript validation inside your VSCode.
Here are the steps that you need to follow:
- Inside your VSCode, go to File > Preferences > Settings
- Search for javascript validate in the search bar.
- Disable the JavaScript validation.
Alternatively, you can add this line to your settings.json file:
json"javascript.validate.enable": false
Note: Disabling this option will silence ALL JavaScript errors and can decrease your overall code quality.
Final thoughts
As you can see, the "type annotations can only be used in typescript files" error has many different fixes.
Which one you choose ultimately depends on your requirements.
Here are some other TypeScript tutorials for you to enjoy: