Photo by ROMAN ODINTSOV from Pexels

Crafting JS Apps with JSDoc and TypeScript

Paul Allies
3 min readNov 26, 2021

There are mixed feelings about using a dynamically typed language like JavaScript when building larger applications. I’m not here to fight for JavaScript over Typescript. I will though illustrate how we can write clean JavaScript and use Typescript and JSDoc to assist in doing so.

As we aim to be clean code developers, we are taught that comments are bad, Commenting code is on the generally-recognized list of code smells.

But not all comments are bad ;)

Enter JSDoc:- JSDoc is a markup language used to annotate JavaScript source code files.

In this post, I illustrate how to use JSDoc to document our code, but rather to help with code completion and type checking.

I use Visual Studio Code, which includes built-in JavaScript IntelliSense out of the box (many other IDEs do the same). VS Code understands many standard JSDoc annotations and uses these annotations to provide rich IntelliSense. We’ll use the type information from JSDoc comments to type check your JavaScript.

Let’s start with a simple example:

Simple JavaScript Function without type checking

The above code is simple: it defines a function, getInfo, that takes in a birthYear and name and returns a message. However, when writing calling code for this function, we need to work out what the input types are based on how they are used within the function.

The calling code

How do we fix this? We need a better way of showing a more informative function signature.

We have 2 ways of doing this: One is to infer type be supplying defaults and the other is to use JSDoc

Using Default Values
Using JSDoc

Now when we write the calling code of this function, it’s more informative

Let’s do another example to show how we can use custom types

Return Type is Person

Here we return a Person type.

We can create a types.d.ts file to keep some or all of our custom types. This file can be stored anywhere and named anything:

We use the typedef import statement to import the type

Last example. We’d like to define a Product Repository and based on that interface build the implementation.

Now let’s create the implementation

Here we create a Product Repository Implementation with data source and notification service dependencies injected through the inputs.

The higher-order function then returns an object of type ProductRepository.

Conclusion

By simply providing enough JSDoc, will give use intelli-sense and type checking across all our JS files, while still keeping code clean and focused

--

--