在我的 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
*/
但是通过这个定义,生日调用都不会标记错误,因为年龄和姓名类型限制被忽略。
带有
的类型定义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)