Search code examples
javascriptvisual-studio-codejsdoc

How to describe an object type that can have additional properties apart from specific ones?


I have a data type called User currently, and I want it to have two mandatory properties, name and age. In addition, users should be able to add any number of other properties to it. How should I describe it in JSDoc to support this requirement without encountering errors?

/**
 * @typedef {object} User
 * @property {string} name - user name
 * @property {number} age -user age
 */

/**
 * @type {User}
 */
const tom={
  name:'cx',
  age:25,
  from:'sh',// error
  to:'bj',// error
}
  

Solution

  • perhaps you can add a {*} property similar to the any-type described here to get rid of the error

    /**
     * @typedef {Object} User
     * @property {string} name - User name (mandatory)
     * @property {number} age - User age (mandatory)
     * @property {*} [key: value] - Additional properties that users can add (optional)
     */
    
    /**
     * @type {User}
     */
    const tom = {
      name: 'cx',
      age: 25,
      from: 'sh', // No error
      to: 'bj', // No error
    };
    

    Edit: after some searching, I've found this thread. Could you check if this resolves the errors

    /**
     * @typedef {object} User
     * @property {string} name user name
     * @property {number} age user age
     */
    
    /**
     * @typedef {Object.<string, string>} Descriptor
     * @typedef {User & Descriptor} UserWithDetails user with details
     */
    
    
    /**
     * @type {UserWithDetails}
     */
    const tom = {
      name: "cx",
      age: 25,
      from: "sh",
      to: "bj",
    };
    

    Edit on edit: If the above works perhaps you can even simplify it by doing

    /**
     * @typedef {object} User
     * @property {string} name - User name
     * @property {number} age - User age
     * @property {Object.<string, string>} [additionalProperties] - Additional key-value pairs
     */
    
    /**
     * @type {User}
     */
    const tom = {
      name: "cx",
      age: 25,
      from: "sh",
      to: "bj",
    };