TypeScript VS - 编译错误,但没有设计时错误



在Visual Studio 2017中,我正在尝试使用ES2015 Promises。使用 TypeScript 2.1.5。我在解决方案中有一个 tsconfig.json 文件,它看起来像这样:

{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"outFile": "outfile.js",
"lib": [ "dom",  "es2015.promise", "es5" ]
},
"exclude": [
"node_modules",
"wwwroot"
]
}

我编译,我得到打字错误,例如:

错误 TS2339:生成:类型上不存在属性"then" "承诺"。

当我转到错误时,我有智能感知显示它实际上确实识别了当时的功能,我可以右键单击,转到定义,这将我带到lib.es2015.promise.d.ts。

为什么设计时有效而编译时无效,我该如何解决?

名为libstsconfig.json属性 - 链接到可怕的官方 tsconfig 文档 - 只是提供类型,例如,您的开发环境可以转到类型定义、推断类型和自动完成代码。它不会将这些类的实现填充到内置 JS 代码中;在许多情况下,目标环境(例如浏览器)提供了自己的Promise实现,因此没有必要。填充是留给开发人员的责任:(

以下是提供甚至可以编译到 ES3 的Promise的方法......

步骤 1:安装提供Promise的填充程序

在项目根目录中,运行以下命令(假设您在那里有一个package.json):

npm install --save es6-promise

步骤 2:使其可用于代码

将此行添加到任何使用Promise.ts文件中:

import {Promise} from 'es6-promise';

步骤 3:让tsc编译器知道键入

我将在此处编辑您当前的tsconfig.json文件:

{
"compilerOptions": {
// I've moved "noImplicitAny" to below.
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es3", // We can target ES3 with this method, if we want!
"outFile": "outfile.js",
/* From http://stackoverflow.com/a/32410515/5951226 : part of this block adds support for ES6 Promises */
"noImplicitAny": false,
"declaration": false,
"module": "commonjs",
"noLib": false
},
"exclude": [
// "node_modules", // We'll need to include "node_modules/es6-promise", so I'll leave it to you to play around with your inclusions/exclusions which are unique to your own use case.
"wwwroot"
]
}

如果您确实需要排除node_modules(我认为这是一个不常见的用例 - 当然您可以解决这个问题..?),您可以将es6-promise库移动到单独的位置并从该位置专门导入,而不是使用自动模块分辨率。

最新更新