nodejs type annotations in vanila js variables and params

Node.js Type Annotations in Vanilla JavaScript Variables and Parameters

If you are working with Node.js or any JavaScript-based application, you might have heard about type annotations. Type annotations are a way to define the expected data type of a variable or parameter in your code.

In vanilla JavaScript, we don't have built-in support for type annotations. However, we can use various techniques to achieve similar behavior. In this article, we will explore some of the ways to add type annotations to vanilla JavaScript variables and parameters.

Using JSDoc Annotations

JSDoc is a markup language used to annotate JavaScript code. It provides a way to add documentation and metadata to your code using comments. JSDoc also supports type annotations, which can be used to define the expected data type of a variable or parameter.

Here's an example:


/**
 * @param {string} name
 */
function sayHello(name) {
  console.log("Hello, " + name);
}

sayHello("Raju"); // Output: Hello, Raju
sayHello(123); // Output: Error: Argument 'name' must be a string

In the above example, we have defined a function called sayHello, which takes a parameter called name. We have added a JSDoc annotation before the function definition to specify that the name parameter should be of type string.

When we call the function with a valid string argument, it works as expected. However, if we pass a non-string value, it throws an error. This is because the JSDoc annotation enforces the expected data type of the parameter.

Using TypeScript

TypeScript is a superset of JavaScript that offers additional features like static typing, interfaces, and classes. If you are using TypeScript in your project, adding type annotations to variables and parameters is straightforward.

Here's an example:


function sayHello(name: string): void {
  console.log("Hello, " + name);
}

sayHello("Raju"); // Output: Hello, Raju
sayHello(123); // Output: Error: Argument of type 'number' is not assignable to parameter of type 'string'

In the above example, we have defined a function called sayHello, which takes a parameter called name. We have used TypeScript syntax to specify that the name parameter should be of type string.

When we call the function with a valid string argument, it works as expected. However, if we pass a non-string value, it throws an error. This is because TypeScript enforces the expected data type of the parameter.

Conclusion

In this article, we have explored some of the ways to add type annotations to vanilla JavaScript variables and parameters. Although vanilla JavaScript doesn't have built-in support for type annotations, we can use JSDoc annotations or TypeScript syntax to achieve similar behavior.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe