英文:
How to describe an object type that can have additional properties apart from specific ones?
问题
/**
- @typedef {object} User
- @property {string} name - 用户姓名
- @property {number} age - 用户年龄
- @property {*} [from] - 用户来自哪里
- @property {*} [to] - 用户要去哪里
*/
<details>
<summary>英文:</summary>
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
}
</details>
# 答案1
**得分**: 1
也许你可以添加一个类似于[这里](https://jsdoc.app/tags-param.html)描述的任意类型的`{*}`属性,以消除错误。
```js
/**
* @typedef {Object} User
* @property {string} name - 用户名(必填)
* @property {number} age - 用户年龄(必填)
* @property {*} [key: value] - 用户可以添加的附加属性(可选)
*/
/**
* @type {User}
*/
const tom = {
name: 'cx',
age: 25,
from: 'sh', // 没有错误
to: 'bj', // 没有错误
};
编辑:经过一些搜索,我找到了这个帖子。你能否检查是否解决了错误。
/**
* @typedef {object} User
* @property {string} name 用户名
* @property {number} age 用户年龄
*/
/**
* @typedef {Object.<string, string>} Descriptor
* @typedef {User & Descriptor} UserWithDetails 带有详细信息的用户
*/
/**
* @type {UserWithDetails}
*/
const tom = {
name: "cx",
age: 25,
from: "sh",
to: "bj",
};
编辑后的编辑:如果上面的方法有效,也许你甚至可以通过以下方式简化它。
/**
* @typedef {object} User
* @property {string} name - 用户名
* @property {number} age - 用户年龄
* @property {Object.<string, string>} [additionalProperties] - 附加键值对
*/
/**
* @type {User}
*/
const tom = {
name: "cx",
age: 25,
from: "sh",
to: "bj",
};
英文:
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",
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论