我开始在一个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命令之前?


当前回答

对于windows中的VS code,单击“设置”。然后在顶部的搜索栏中,输入javascript validate,然后取消选中如下所示的复选框。

其他回答

[Mac]在Visual Studio Code中键入以下命令。

command + shift + P 然后在VS Code顶部的搜索栏中输入“Preferences: Open User Settings (JSON)” 添加一行-> "javascript.validate。启用”:假

注意:“首选项:打开默认设置(JSON)”是不可编辑的

您必须使用.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的上下文,请补充。让我们一起学习。

我使用流量与vscode,但有同样的问题。我通过以下步骤解决了这个问题:

安装扩展流语言支持 禁用内置的TypeScript扩展: 进入扩展选项卡 搜索@内置TypeScript和JavaScript语言特性 点击禁用

“typescript.validate。启用”:假

IN VS Code ->首选项->设置->搜索上述属性并禁用该属性

只需要将变量默认为预期的类型:

(number=1) => ...
(number=1.0) => ...
(string='str') ...