我开始在一个Node项目中使用TypeScript,我正在Visual Studio Code中工作。我想遵循“选择加入”策略,类似于“心流”。因此,我把// @ts-check放在我的.js文件的顶部,希望为该文件启用TS。最终,我想要与Flow相同的“检测”体验,因此我安装了插件TSLint,这样我就可以看到智能感知警告/错误。
但我的文件是这样的:
// @ts-check
module.exports = {
someMethod: (param: string): string => {
return param;
},
};
还有我的tsconfig。Json文件看起来像…
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"allowJs": true
}
}
我得到这个错误:[js] 'types'只能在.ts文件中使用。如下图所示。
我看到这个问题,建议在vscode中禁用javascript验证,但这并没有显示我任何TypeScript智能感知信息。
我试着设置切线。jsEnable在我的vscode设置中为true,正如在TSLint扩展文档中提到的,但没有运气。
什么是正确的设置,以便使用.js文件与TypeScript,并获得智能感知,让我知道我的代码中的错误是在我运行任何TS命令之前?
您必须使用.ts文件-例如test。ts来获得Typescript验证,智能感知vars类型,返回类型,以及“类型化”错误检查(例如,将字符串传递给一个期望数字参数的方法将出错)。
它将通过tsc转译为(standard) .js。
更新(11/2018):
根据反对票,非常有用的评论和其他回答,需要澄清。
类型
Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation
What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
如果我遗漏了一些内容,包括这些内容以及OP的上下文,请补充。让我们一起学习。