VSCode 版本:1.20.0
首先,我认为我对 Visual Studios Code IntelliSense 的了解:
tsconfig.json
的存在/jsconfig.json
应该向 vscode 指示该目录是一个 TypeScript/JavaScript 项目 ( docs )。这意味着 IntelliSense 应该知道所有.js
和.ts
目录中的文件(关于include
和exclude
配置属性),以及这些文件导出的所有类/定义,而无需显式引用它们。- 在任何情况下,您都可以通过显式引用文件使 IntelliSense 知道文件导出的类/定义。这可以通过
require()
完成,import
, 或/// <reference path="..." />
. - 您可以混合使用 TypeScript 和 JavaScript 文件。
鉴于这些先入之见,我无法让 vscode 按预期工作。请参阅下面的简单示例项目。目标是能够使用 Person
test.d.ts
中定义的类定义test.js
中的类型化定义 TypeScript 文件JavaScript 文件。但是,IntelliSense 提示它不知道 Person
类:
请注意,IntelliSense 适用于 npm install
的包-编辑。
给定假设 #1,只需包含 tsconfig.json
文件应该是我所需要的。即便如此,我也尝试明确列出 typings/test.d.ts
和 test.js
在 includes
.我也试过列出 typings
在 compilerOptions.typeRoots
.
给定假设 #2,包括 test.js
中的三斜线引用指令至 ./typings/test.d.ts
应该可以。
那里有很多过时的信息,因为 vscode 已经改变了它处理配置、类型等的方式。我已经阅读了我能找到的所有内容,但我无法让它工作。
有什么想法吗?我在这里缺少什么?
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": ["es6"],
"allowJs": true,
"checkJs": true
},
"exclude": [
"node_modules"
]
}
test.js
/// <reference path="./typings/index.d.ts" />
/** @type {Person} */
const p = {};
typings/test.d.ts
export class Person {
name: string;
age: number;
}
最佳答案
截至 2018 年 5 月 (v1.24) 版 VSCode,TypeScript 版本已更新至 2.9,其中包括 import()
类型的功能。
这意味着我们也可以像这样在 JSDocs 中使用 import()
:
/** @type {import('./typings/test').Person} */
const p = {};
和/或
/** @typedef {import('./typings/test').Person} Person */
/** @type {Person} */
const p = {};
这也允许我们引用在其他 JavaScript 文件中定义的类型,即使它们没有被导出。不需要 tsconfig.json
或任何其他配置文件,也不需要使用 TypeScript 文件。完整示例:
func1.js
/**
* @typedef MyStruct
* @property {string} fu
* @property {number} bar
*/
module.exports = function func1() {
// ...
}
func2.js
/**
* @param {import('./func1').MyStruct} options
*/
module.exports = function func2(options) {
// ...
// IntelliSense definition for this function:
// func2(options: MyStruct): void
}
您还可以从节点模块中引用类型:
/** @type {import('async').AsyncCargo} */
注意:我确实发现了一个可能的错误。如果您 import()
的文件没有导出任何内容,智能感知就会中断。
关于typescript - vscode 在 JavaScript 文件中使用类型化定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693880/