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


当前回答

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

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

其他回答

我遵循以下步骤来解决这个问题:

进入“首选项”,然后进入“设置”:

进入设置后搜索javascript。在搜索栏中验证并取消复选框:

如果你想通过json编辑它,那么: 转到:代码->首选项->设置->扩展->向下滚动,找到“在设置中编辑。json”。 然后添加

"javascript.validate.enable": false

您必须使用.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语言特性 点击禁用

去设置和搜索javascript验证,然后禁用选项来修复这个问题。

类型/接口只能应用于TypeScript文件,而.js文件是JavaScript文件。

所以解决方案很简单:

将扩展名.js更改为.tsx以使用类型/接口。