Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 18, 2021 05:03 pm GMT

Get types by Writing Hybrid JavaScript

introduction

We all know the frustration caused by not having typed JavaScript, it's also one of the main reasons why people tend to switch to typescript to gain access to live code error prediction and of course types.

The problem with typescript is that you have to compile your code, add a tsconfig.json file, fix non typed modules, and integrate a lot of code to your JavaScript to make the compiler happy.

But wait, there is a solution!

JsDoc

To start gaining access to types without typescript, you have to use jsdoc

JsDoc is originally built to allow you to document your JavaScript code using comments, but you can use it to type your code.

JsDoc syntax

You start a JsDoc comment with /**, each new line starts with * and it ends with */

/** *  *  *  */// OR/** */

If you are in vscode it will automatically detect that you are writing a JsDoc comment and add * to each new line.

JsDoc Tags

JsDoc uses tags to type your code, we will focus on two of them but feel free to check on the 65 others in JsDoc Docs.

A tag contains a @, the tag name, and the arguments.

To type a function parameter, use the @param tag followed by a TypeScript type in brackets and the name of the parameter:

/** * * @param {string} name */function say_hello(name){    console.log("hello" + name);}

And you get autocompletion and types:
vscode preview

You can also use it with complex types, for example in a discord bot:

import Discord from "discord.js";/** * * @param {Discord.Client<boolean>} client * @param {Discord.Message} message */async function ban (client, message) {}

vscode preview

To type a variable, use the @type tag:

/** @type {string} */let name;

Custom types

You can also use custom types using typescript interfaces:

/** @type {{ *  name: "string"; *  age: number; *  interests: { *     [key: string]: number; *  } * }} */let user;

vscode preview

using declaration files

Writing types like this works great, but you will soon realize that there is a lot of repetition when you are using the same custom type and that your code is cluttered.

The solution is to use TypeScript declaration files.

Just create a file in your project ending in .d.ts and declare your types in it using typescript types

// types.d.tsdeclare type User = {  name: string;  age: number;  interests: {    [key: string]: number;  };};

Once that's done, you will be able to reference the User type directly:

/** @type {User} */let user;

vscode preview


Original Link: https://dev.to/rafaelmc/writing-hybrid-javascript-10mk

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To