Typing your JavaScript without writing TypeScript

Shivam SharmaShivam Sharma
2 min read

Table of contents

The good news is that we can give TypeScript more hints about the types that flow around our JavaScript application or project without changing the project to TypeScript.

JSDoc

You can use JSDoc to set the types of variables. In this example, assigning an empty array to the variable fruits don't tell the type system anything, but if we use the JSDoc @type annotation, then we indicate to TypeScript that this variable should only be an array of strings.

// @ts-check
/**
 *  @type {Array<string>}
 */
let fruits = [];

If you later try to assign a value with a different type to fruits or try to add an element of the wrong type, TypeScript will complain about it. See the following example which we have declared our array type of string but we are assigning to it number

You can also define complex types with @typedef.

// @ts-check
/**
 * @typedef {object} TeamMember
 * @property {string} name - the full name of a team member
 * @property {Array<string>} languages - the programming languages the member knows
 */

/**
 * @type {TeamMember}
 */
const teamMember = {
  name: "Shivam Sharma",
  languages: ["Java", "JavaScript", "TypeScript", "CSS", "HTML"],
};

With JSDoc annotations in place, you can import types from one file into another, meaning you don't have to repeat yourself and redefine types in multiple places.

You can also type the parameters and the return value of functions:

/**
 * @typedef {import("./teamMember").TeamMember} TeamMember
 * @param {Array<TeamMember>} teamMembers - a list of team members
 * @returns {Array<string>}
 */

function getNames(teamMembers) {
  return teamMembers.map(tm => tm.name);
}

There's more to JSDoc than this, and you can read up on the JSDoc annotations that TypeScript supports in the TypeScript documentation.

1
Subscribe to my newsletter

Read articles from Shivam Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shivam Sharma
Shivam Sharma

I’m an Open-Source enthusiast & Final year pursuing my Bachelors in Computer Science. I am passionate about Kubernetes, Web Development, DevOps & I enjoy learning new things.