SonarSource sponsored this post. Insight Partners is an investor in SonarSource and TNS.
You know that TypeScript gives the advantages of type safety and confidence from potential bugs. But what you don’t know is that you can still accomplish many of the same things in JavaScript as you can in TypeScript … without writing in TypeScript itself.
The more information you can give TypeScript, the better it understands your JavaScript, which helps your IDE to make better suggestions. By inferring types across a codebase, TypeScript can highlight unexpected behavior in JavaScript code, meaning it can help catch bugs earlier.
The question is: How can we push TypeScript’s advantages to get even more out of tooling in our JavaScript projects?
Configuring Your Editor for TypeScript
The easiest way to get more insight from TypeScript is to configure your editor to use TypeScript to analyze the JavaScript you’re writing.
With VS Code, adding the comment // @ts-check to the top in any JavaScript file you’re writing will tell TypeScript to analyze its contents and let you know where things look out of place. Remember that you only get this analysis in the individual files where the comment is added. And if you’re going to add TypeScript comments to a codebase, make sure everyone on your team is aware.
VS Code also allows you to turn on TypeScript checking for all JavaScript without changing the source code. Just open up the settings and search for “Check JS.” This setting (JS/TS › Implicit Project Config: Check JS) can be enabled for the workspace or at the user level. For the workspace, VS Code will use TypeScript to type-check all the open files in the project, and at the user level, it will use TypeScript to check all your projects as you work on them.
With this, you’ll learn more about your JavaScript and reduce issues as you go without adding config to your application. Best of all, this won’t break your build — it’s only visible in your editor.
Sonar equips developers and organizations to deliver quality, secure code fit for development and production, whether AI-generated or written by developers. Trusted by over 400,000 organizations globally to clean more than half a trillion lines of code, Sonar is integral to delivering software. Insight Partners is an investor in SonarSource and TNS.
Learn More
The latest from SonarSource
Introducing TypeScript Directly into the Project
Next, you can introduce TypeScript directly into your project. With that, your whole team can use this tool. Later in this article, you’ll see that you can even start to add more types, all without changing a single file type to .ts.
To do this, you’ll need to install TypeScript as a dependency in your project. You can do this with the command npm install typescript --save-dev. Next, create a tsconfig.json file. Run this command: npx tsc --init. Then, open up the newly generated tsconfig.json file. The default settings here are good when you start a new TypeScript project, but you’ll need to change some options to handle a JavaScript project. Update your tsconfig.json to this:
1
2
3
4
5
6
7
8
9
10
11
{
"compilerOptions":
{
"allowJs":
true,
"checkJs":
true,
"noEmit":
true,
"esModuleInterop":
true,
"forceConsistentCasingInFileNames":
true,
"strict":
false,
"skipLibCheck":
true
}
}
Make sure to include allowJS and checkJS to permit JavaScript to be part of a TypeScript application, and then apply type-checking to JavaScript files. The checkJS setting is the same as enabling Check JS in your VS Code settings. Important note: Having a tsconfig.json file with these settings overrides the VS Code settings and enables TypeScript checking in other editors.
The setting noEmit is part of this because, at this point, we just want to type-check the JavaScript. The TypeScript compiler won’t try to output anything — it’ll only report on the JavaScript it reads. Additionally, Strict is set to false because getting JavaScript code to adhere to TypeScript’s strict mode is challenging otherwise.
Finally, add a script to your package.json to run the type checker, like this:
1
2
3
"scripts":
{
"type-check":
"tsc"
}
Now you can run npm run type-check and see the results.
Fix Missing Types and the Code
Since TypeScript hasn’t been used in your project, you’ll probably need to fix some things. If you’re working with Node.js, you’ll need to add TypeScript types for Node.js. It’s as easy as running npm install @types/node --save-dev.
These types come from Definitely Typed, a comprehensive community effort to provide types for modules that don’t provide their own. If Definitely Typed has a type for your module, you can install it in your project from the @types scope. If you want, you can also add types for packages you use that don’t provide types themselves from Definitely Typed.
If you don’t install the types, TypeScript will consider imports from packages as an any type (TypeScript’s catch-all type). It lets the program compile but doesn’t give you any further information about the objects you’re using. When you add or define types for these packages, TypeScript can then help with autocomplete and highlighting potential issues. I’d recommend installing the types for your dependencies as you come to work on the parts of the source code that use them.
Next, you might find TypeScript is reporting some errors in your code. That’s exactly what we want.
Any issue raised is a potential runtime bug in your application that TypeScript has now detected. You can see these errors in your editor or when you run the type-check script. Fixing these errors will improve the reliability of your application. Now that TypeScript is part of your project, issues like these shouldn’t slip through.
Add to the Build Process
Once the type-checking process returns successfully, you may want to add the check to your build process. This ensures that your codebase stays as type-safe as it can be for a JavaScript project.
How you achieve this depends on your existing testing and build process. One option is to run the type-checking process as part of your test suite.
Reaping More Advantages for Your JavaScript
As we’ve discussed, you don’t have to move your project from JavaScript to TypeScript to get the benefits; you can just get the TypeScript compiler to help. Both the Webpack and Svelte projects organize themselves like this. Check out their source code, JavaScript files for code and TypeScript declaration files for the types.
Once you’ve made it to this stage, you might want to make your JavaScript even more safe by adding further types.
Adding More Types
JSDoc lets you document your code through machine-readable comments. Although initially built to generate API documentation for your code, TypeScript has adopted it as a way to provide type information in JavaScript files.
JSDoc can help you set the types of variables. For example, assigning an empty array to a variable doesn’t tell the type system anything. If you use the JSDoc @type annotation you can tell TypeScript what type the contents of the array will be. And because this is documentation, it also tells you and your team what kind of variable this is.
If you later violate the type that you defined with JSDoc, TypeScript will let you know. You can also define complex types with @typedef, type functions using @param and @returns, and import types from one file into another.
JSDoc can do even more with TypeScript. You can learn about it in the TypeScript reference for JSDoc.
Declaration Files
If writing type definitions in comments in your files feels like too much work to be worth it, you can write them in a declaration file instead. These are the .d.ts files you’ll find in Definitely Typed or in JavaScript libraries. These declaration files are the closest we’ll get this time to writing TypeScript itself.
For example, to define a TeamMember type, just create a teamMember.d.ts file and enter the following:
1
2
3
4
export type TeamMember=
{
name:
string;
languages:
Array<string>;
};
Then you can import that into your JavaScript using the JSDoc import syntax.
This keeps your type definitions separate from your code but gives you all the expressiveness of the TypeScript system. And adding type definitions to your libraries means that other projects can access the types too.
Advantages for Supercharging Your Code
By taking advantage of TypeScript in your JavaScript projects, you can help improve your code as you go, saving you time and effort on your projects now and in the future. By doing so, you’ll be able to write cleaner, more intentional code that leads to better, more reliable applications.
Sonar equips developers and organizations to deliver quality, secure code fit for development and production, whether AI-generated or written by developers. Trusted by over 400,000 organizations globally to clean more than half a trillion lines of code, Sonar is integral to delivering software. Insight Partners is an investor in SonarSource and TNS.
Learn More
The latest from SonarSource
TRENDING STORIES
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don't miss an episode. Subscribe to our YouTube channel to stream all our podcasts, interviews, demos, and more.
Phil Nash is a developer advocate for Sonar serving developer communities in Melbourne and all over the world. He loves working with JavaScript or Ruby to build web applications and tools to help developers. He can be found hanging out...