JSDoc @param as a predefined constant object

Viewed 365

Let's say I have a predefined constant object like this:

const person = {
   name: "",
   gender: "",
   age: 0
}

Then I have a function that requires the parameter must be the type of person:

/**
 * @param {*} personObj How can we enforce the personObj as the type of an existing constant object?
 */
function approve(personObj) {

}

How can I enforce the personObj to be the type of person? Is it possible to avoid using @typedef? Because I have many predefined constant objects of such that we do not want to rewrite all the definitions again. Any advice would be appreciated, thank you!

2 Answers

You can achieve this with 2 different approaches:

  1. Define the types in jsdoc comments as follows
/**
 * @param { { name: string, gender: string, age: number } } personObj Person Object
 */
function approve(personObj) {
   // do stuff with personObj
}

All the popular Editors and IDE's will show the above-mentioned comments in a formatted way.

  1. Write a module.d.ts file

You can also add a declaration file that defines all the type definitions used inside a module.

Create a module.d.ts file and declare your Module

// module.d.ts

export interface Person {
  name: string;
  gender: string;
  age: number
}

Your code editor will use this declaration file to provide you with the hints and checks you need in your code.

More about declaration files here

You can try something like this

/**
 * @param {Object<name:string,gender:string,age:number>} personObj 
 */

function approve(personObj) {

}
Related