在 JSDoc 中,如何记录一个同时采用特定类型的可选命名属性和未知属性的对象

问题描述 投票:0回答:1

在我的 JavaScript 模块中,我在 JSDoc 中定义了一个在函数中使用的对象类型:

//@ts-check

/**
 * @typedef {Object} Person
 * @property {number} age
 * @property {string} name
 */

/**
 * Birthday wishes to period
 * @param {Person} person
 */
function birthdayWish(person) {
    return 'Happy birthday number'+person.age+', '+person.name;
}

当我调用此函数时,我希望能够拥有其他属性而不会导致错误:

birthdayWish({'name':'Sam', 'age':35, 'occupation':'teacher'})
// Want this to work but it produces a TypeScript error

但我确实希望命名属性强制遵循类型:

birthdayWish({'name':'Joe', 'age':'hmm', 'occupation':'lawyer'})
// Want this to be an error because age is the wrong type

有没有办法定义 Person 来允许这样做?

我尝试将 typedef 更改为:

 /**
 * @typedef {Object.<string, *>} Person
 * @property {number} age
 * @property {string} name
 */

但是通过这个定义,生日调用都不会标记错误,因为年龄和姓名类型限制被忽略。

javascript typescript visual-studio-code jsdoc
1个回答
0
投票

解决方案

带有

optional property

的类型定义
//@ts-check

/**
 * @typedef {Object} Person
 * @property {number} age
 * @property {string} name
 * @property {string} [occupation]
 */

/**
 * Birthday wishes to period
 * @param {Person} person
 */
function birthdayWish(person) {
  return 'Happy birthday number'+person.age+', '+person.name;
}


birthdayWish({'name':'Sam', 'age':35, 'occupation':'teacher'})


birthdayWish({'name':'Joe', 'age':'hmm', 'occupation':'lawyer'})
// Type 'string' is not assignable to type 'number'.ts(2322)

参考

https://jsdoc.app/tags-property.html

© www.soinside.com 2019 - 2024. All rights reserved.