在 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"
]
}
我编译,但出现输入错误,例如:
error TS2339: Build:Property 'then' does not exist on type 'Promise'.
当我遇到错误时,我有 intellisense 显示它实际上识别了 then 函数,我可以右键单击,转到定义,这会将我带到 lib.es2015.promise.d.ts。
为什么设计时有效而编译时无效,我该如何解决?
最佳答案
名为 libs
的 tsconfig.json
属性——链接到可怕的官方 tsconfig 文档 here – 仅提供类型,例如,您的开发环境可以转到类型定义、推断类型和自动完成代码。它不会将这些类的实现填充到您的内置 JS 代码中;在许多情况下,目标环境(例如浏览器)提供了它自己的 Promise
实现,因此没有必要。 Shimming 是留给开发人员的责任:(
这是提供 Promise
的方法,它甚至可以编译成 ES3...
第 1 步:安装提供 Promise
的 shim
在您的项目根目录中,运行此命令(假设您在那里有一个 package.json
):
npm install --save es6-promise
第 2 步:使其可用于您的代码
将此行添加到任何使用 Promise
的 .ts
文件:
从'es6-promise'导入{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
库到一个单独的位置,并专门从该位置导入,而不是使用自动模块解析。
关于visual-studio - TypeScript VS - 编译错误但没有设计时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909362/