[英]Visual Studio Code - TypeScript type checking - recognize external objects in JavaScript project
Have enabled TypeScript checking in a JavaScript-only project in VS Code using the global setting 使用全局设置在VS Code中的纯JavaScript项目中启用了TypeScript检查
"javascript.implicitProjectConfig.checkJs": true “ javascript.implicitProjectConfig.checkJs”:是
The type checking works, but for every external/global variable it shows a 'cannot find name' error: 类型检查有效,但是对于每个外部/全局变量,它都会显示“找不到名称”错误:
$('body').addClass('something'); $('body')。addClass('something'); // cannot find name '$' //找不到名称“ $”
MyCustomObject.doSomething(); MyCustomObject.doSomething(); // cannot find name 'MyCustomObject' //找不到名称“ MyCustomObject”
How can I make VS Code recognize these global variables ? 如何使VS Code识别这些全局变量? I think that this needs to be done using a custom definition file specified in a jsconfig.json, but haven't been able to make it work. 我认为需要使用jsconfig.json中指定的自定义定义文件来完成此操作,但尚未使其能够工作。
UPDATE: 更新:
Not a duplicate of Enabling implicit type checking for Javascript in VS Code results in "Cannot find name 'require'" error . 与在VS Code中启用Java的隐式类型检查不同,这会导致“找不到名称'require'”错误 。
Have seen that ticket and it is related only to a node.js project and the accepted answer is related to installing the type definition npm package for nodejs. 已经看到了该票证,它仅与node.js项目有关,可接受的答案与为nodejs安装类型定义npm软件包有关。 Which is not the case here. 这里不是这种情况。 I need to set up a custom defintion file 我需要设置一个自定义文件
You can declare global types as shown in https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html 您可以声明全局类型,如https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html中所示
Keep the declared types as any
so that tsc doesn't complain about not being a function or not having properties. 保持声明的类型为any
类型,以便tsc不会抱怨不是函数或没有属性。
Create an index.d.ts file in the root folder with content 在根文件夹中创建带有内容的index.d.ts文件
declare global {
var $: any;
var MyCustomObject: any;
}
export {};
After changing the index.d.ts file restart VSCode to make it recognize the types. 更改index.d.ts文件后,重新启动VSCode以使其识别类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.