1

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 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, is this type script? I never use typescript before. If my node.js project has not been setup for typescript, can I still use approach #2? In module.d.ts, what is d stands for? Can it be anything?
Yes, this is typescript file, The purpose of declaration files is to introduce types in javascript code. d stands for declaration. you can name your file anything as *.d.ts where asterisk can be replaced by your module name. You need to use namespace declarations. You can follow the link I've added to look into ts docs
0

You can try something like this

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

function approve(personObj) {

}

1 Comment

Ya, I'm aware of this, but if I have many functions that make use of Person parameter, then I'll have to rewrite the definition as @param for all the functions. Any change of structure needs to change the JSDoc for all functions again...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.