假设我有一个预定义的常量对象,如下所示:
const person = {
name: "",
gender: "",
age: 0
}
然后我有一个函数,它要求参数必须是person
:的类型
/**
* @param {*} personObj How can we enforce the personObj as the type of an existing constant object?
*/
function approve(personObj) {
}
如何将personObj
强制为person
的类型?是否可以避免使用@typedef
?因为我有很多预定义的常量对象,所以我们不想再次重写所有的定义。任何建议都将不胜感激,谢谢!
您可以通过两种不同的方法来实现这一点:
- 在
jsdoc
注释中定义类型如下
/**
* @param { { name: string, gender: string, age: number } } personObj Person Object
*/
function approve(personObj) {
// do stuff with personObj
}
所有流行的编辑器和IDE都将以格式化的方式显示上述评论。
- 编写
module.d.ts
文件
您还可以添加一个声明文件,该文件定义模块中使用的所有类型定义。
创建一个module.d.ts
文件并声明您的模块
// module.d.ts
export interface Person {
name: string;
gender: string;
age: number
}
您的代码编辑器将使用此声明文件为您提供代码中所需的提示和检查。
更多关于这里的申报文件
您可以尝试类似的
/**
* @param {Object<name:string,gender:string,age:number>} personObj
*/
function approve(personObj) {
}