Sobes.tech
Junior — Middle

How to declare a method parameter of arbitrary type as mandatory?

sobes.tech AI

Answer from AI

In JavaScript (Node.js), to make a parameter of arbitrary type mandatory in a method, you usually just declare the parameter in the function's argument list. Since JavaScript is dynamically typed, the parameter can be of any type. To make the parameter mandatory, you can check its presence and throw an error if it is not provided:

function example(param) {
  if (param === undefined) {
    throw new Error('Parameter is required');
  }
  // work with param of any type
  console.log(param);
}

example(123); // works
example(); // throws an error

If using TypeScript, you can specify the type any or a generic type so that the parameter can be of any type, and make it mandatory:

function example(param: any): void {
  console.log(param);
}

Here, param is required and can be of any type.

How to declare a method parameter of arbitrary type… - sobes.tech