TypeScript Promise TS2304 TS2529 [英] TypeScript Promise TS2304 TS2529

查看:255
本文介绍了TypeScript Promise TS2304 TS2529的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

function asyncFunc1(): Promise<string> {
    return new Promise<string>(x => x);
}

产生以下错误:


TS2304:找不到名字'承诺'

TS2304: cannot find name 'Promise'

所以我把它改为显式声明'承诺':

So I changed it to explicitly declare 'Promise':

///<reference path="../typings/modules/bluebird/index.d.ts" />

import * as Promise from 'bluebird';

function asyncFunc1(): Promise<string> {
    return new Promise<string>(x => x);
}

现在我收到以下错误:


TS2529:重复标识符'Promise'。编译器保留名称
'Promise'在包含异步函数的模块的顶级范围内

TS2529: Duplicate identifier 'Promise'. Compiler reserves name 'Promise' in top level scope of a module containing async functions

如何解决这个矛盾?

推荐答案

承诺仅适用于ES6



如果您设置了作为ES6的目标,typescript编译器使用不同的基本库来对照语言规范中包含的类型进行基本类型检查。确保您的目标是ES6。

Promises are only available in ES6

If you set the target to ES6, the typescript compiler uses a different base library to for basic type checking against types included in the language specification. Make sure you are targeting ES6.

如果您想要访问定义构造函数作为es2015规范中定义的方法,已经由浏览器和NodeJS(通过V8引擎)在语言功能(如箭头函数,解构等)之前实现 - 您可以这样做。

If you want access to definition of Constructors as methods defined in the es2015 specification, that have been implemented by browsers and NodeJS (via V8 engine) before language features - like arrow functions, destructuring, etc - you can do that.

你想要做的是将TypeScript配置为目标es5,而不是include和默认库,并自己引用默认库。

What you want to do is configure TypeScript to target es5, not include and default library, and reference the default library yourself.

你的tsconfig可能看起来像这个:

Your tsconfig might look something like this:

{
  "compilerOptions: {
    "noLib": true,
    "target": "ES5",
    }
   "files": [
     "node_modules/typescript/lib/lib.es6.d.ts",
     "app.ts",
   ]
}

以上示例假设打字稿直接安装在你的项目。如果不是,你可以随时从你的打字稿安装复制lder并将其包含在你的项目中。

The above examples assumes that typescript is installed directly in your project. If it is not you can always copy from your typescript installation's folder and include it in your project.

这个解决方案应该为你提供Promise构造函数的输入,以及各种其他功能,如array.includes()和a其他一些事情。这有一个缺点,你不会因为浏览器中没有实现的东西而出现类型错误,但是如果你使用Promise,你可能只是针对现代浏览器,或者你正在使用你控制的Node运行时环境。

This solution should give you typings for the Promise constructor, as well as a variety of other features like array.includes() and a few other things. This comes with the downside that you won't get type errors for things that are not implemented in the browsers, but if you're using Promise anyway you're probably targeting modern-browsers only, or you're using Node where you control the runtime environment.

这篇关于TypeScript Promise TS2304 TS2529的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆