How has the recent turmoil within the OpenAI offices changed your plans to use GPT in a business process or product in 2024?
Increased uncertainty means we are more likely to evaluate alternative AI chatbots and LLMs.
No change in plans, though we will keep an eye on the situation.
With Sam Altman back in charge, we are more likely to go all-in with GPT and LLMs.
What recent turmoil?
JavaScript / Software Development / TypeScript

How to Get Advantages of TypeScript in JavaScript

Easy steps to take advantage of TypeScript in your JavaScript projects, without writing in TypeScript.
Oct 27th, 2023 10:51am by
Featued image for: How to Get Advantages of TypeScript in JavaScript

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.

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:

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:

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:

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.

Group Created with Sketch.
TNS owner Insight Partners is an investor in: Pragma, SonarSource.
THE NEW STACK UPDATE A newsletter digest of the week’s most important stories & analyses.