假设我有一个名为“File1.js”的文件。在这个文件中,我导出一个对象的对象,我给每个对象一个 typedef,就像这样。
/**
* My typedef for each object.
* @typedef {Object} MyObject1
* @property {String} username Your username
* @property {String} realname Your real name.
* @property {boolean} isUnique Are you unique as a person?
*/
module.exports = {
/**
* Person One!
* @type {MyObject1}
*/
myperson: {
username: 'TheDragonSlayer',
realname: 'George',
isUnique: true
},
/**
* Person Two!
* @type {MyObject1}
*/
myperson2: {
username: 'BobMagee',
realname: 'Bob',
isUnique: false
}
}
现在,在一个名为“File2.js”的文件中,我在构造函数中引用了这个对象并将其设置为一个新的
MyObject1
.
const persons = require('./File1.js');
class File2 {
constructor(options = {}) {
/**
* The person for this file.
* @type {MyObject1}
*/
this.person = options.person ? persons[options.person] : persons.myperson2;
}
}
module.exports = File2;
我使用 Visual Studio Code 进行开发,因此通过按 Ctrl+Space 我可以获得 IntelliSense。在第一个文件中,当我制作人物对象时,IntelliSense 告诉我 username 是一个字符串,realname 是一个字符串,而 isUnique 是一个布尔值。但是,当我进入 file2 并通过
this.person
引用新创建的人时,当键入 this.person.username
时,它不会出现“用户名:字符串”的预期结果。
是否可以在普通 Node.js 的 File2 中使用 typedef
MyObject1
,还是我运气不好?
编辑:有了更多信息,我能够找到 @export 和 @import for TypeScript 的答案,以及我也尝试过的各种标签。所有这些都无济于事。我还尝试将 File1.js 标记为 @module,并执行
module:mymodule~MyMethod
,但每次我这样做时,它只会将 this.person 标记为 NodeModule 而不是方法本身。
我发现的另一件事是导出和清空模型,然后将其用作对类型的引用:
类型.js:
/**
* @typedef MyType
* @prop {string} name
* @prop {string} description
*/
export const Types = {}
然后在您的其他文件中,您可以导入它并从该虚拟对象中获取类型:
File1.js
import * as Types from "./types.js"
/** @type {Types.MyType} */
const myVar = { name : 'Roy', description : 'abc123'};
优点:
缺点:
此导入从不用作值,必须使用“导入类型” 因为 'importsNotUsedAsValues' 设置为 'error'
如果你有那面旗帜。
要绕过该警告,您只需使用 ts-ignore 禁用它:
// @ts-ignore
import * as Types from "./types.js";