0

How can I describe what parameters my function requires and make them viewable when i type my code?

  • For example, lets say I want to hint what parameters a callback function would take. If we look at ExpressJS render function below, it shows exactly what the callback accepts and would return.
  • Mine however only says (cb1: any) despite that this callback is supposed to return 2 parameters (error and data). Is there any special way to define it?

enter image description here

enter image description here

Currently the code in my Product model for this function looks like this. How can I define the callback function in a way that it would hint what it returns?

static findById(id, cb1) {
 fs.readFile("./src/database/products.json", (err, data) => {
   if (err) {
     cb1(err, product);
   } else {
     const products = JSON.parse(data);
     const product = products.find(p => p.id == id);
     cb1(err, product);
   }
 });
};
Knightwalker
  • 307
  • 1
  • 4
  • 12

3 Answers3

2

This question might help you : jsdoc and vscode: Documenting a function passed as an argument to another function

1

Use :Javascript documentation starndards

OR You need to use Typescript for define functions interface:

static findById(id: number, cb1: (err: {}, product: {}) => void) {
 fs.readFile("./src/database/products.json", (err, data) => {
   if (err) {
     cb1(err, product);
   } else {
     const products = JSON.parse(data);
     const product = products.find(p => p.id == id);
     cb1(err, product);
   }
 });
};
Ali Eslamifard
  • 565
  • 3
  • 11
1

Alright guys thanks for the help! It seems that just by using jsdocs without typescript is enough. I was not aware of how jsdocs works in vscode. After changing my code to the one bellow I got what I wanted. I will be playing with this more.

/**
* Finds a `product` with the given `id` and executes a callback `fn` containing the result.
* @param {number} id
* @param {(err : Error, product: string) => void} callback
*/
static findById(id, callback) {
  fs.readFile("./src/database/products.json", (err, data) => {
    if (err) {
      callback(err, product);
    } else {
      const products = JSON.parse(data);
      const product = products.find(p => p.id == id);
      callback(err, product);
    }
  });
};

enter image description here

Knightwalker
  • 307
  • 1
  • 4
  • 12