我开始在一个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的上下文,请补充。让我们一起学习。

其他回答

对于任何人谁登陆这里,所有其他解决方案都不工作,请尝试一下。我使用typescript + react,我的问题是我在vscode中关联的文件是javascriptreact而不是typescriptreact,所以请检查以下条目的设置。

   "files.associations": {
    "*.tsx": "typescriptreact",
    "*.ts": "typescriptreact"
  },

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

所以解决方案很简单:

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

“typescript.validate。启用”:假

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

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

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

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

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

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