DEV Community

Cover image for Add typing to your Javascript code (without Typescript, kinda) โœ๐Ÿผ
Nico Montiel
Nico Montiel

Posted on

Add typing to your Javascript code (without Typescript, kinda) โœ๐Ÿผ

Hey there.

I recently started working on a full Javascript project. And after years of working with Typescript, it was strange to work in an environment where no one is telling me "Hey, that property is not there, man".

So I start researching about the better way to do this, without implementing Typescript, because migrating to Typescript is a big job that most of the company doesn't find worthwhile in older projects.

The best way to do this, of course, is with JSDoc. But something I always found awkward about jsdoc is defining the object types in the same file.
So, after a lot of reading, I found a way to combine JSDoc with declaration type files from Typescript. Let me give you an example:

This is your type declaration file, something like types.d.ts



export interface Product {
    sku: string
    name: string
    available: boolean
    price: double
}


Enter fullscreen mode Exit fullscreen mode

This is your javascript file, maybe your index.js



function main() {
    /** @type {import('./types.d.ts').Product} */
    const product = {
        sku: '123',
        name: 'My product',
        available: true,
        price: 12.00
    }
}


Enter fullscreen mode Exit fullscreen mode

So here, if you put a wrong value in the object product, you editor is going to let you know:

Image from vscode showing an error because of the type

That's all, I hope it can be helpful for you ๐Ÿฅณ

Top comments (0)