TypeScript Promise TS2304 TS2529

I had the following code:

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

which caused the following error:

TS2304: Cannot find the 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); } 

and now I get the following error:

TS2529: Duplicate identifier "Promise". The name of the Promise compiler stock in the top-level area of ​​the module containing asynchronous functions

How can I solve this paradox?

+6
source share
2 answers

Promises are available only in ES6.

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

Promises in typescript without ES6 targeting

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

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

Your tsconfig might look something like this:

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

The examples above assume that typescript is installed directly in your project. If this is not the case, you can always copy from the typescript installation folder and include it in your project.

This solution should give you typing for the Promise constructor, as well as many other functions like array.includes () and a few other things. This is due to the drawback that you will not get type errors for things that are not implemented in browsers, but if you use Promise, you will probably focus only on modern browsers or use Node, where you control the runtime.

+4
source

TypeScript seems to protect the Promise identifier. Try importing as a name other than the promise, or use a different typing set. There are several suggestions for this TypeScript GitHub issue.

Async / waiting with Bluebird promises

The problem is using a different promise library with Async Await, but this is probably why they protect the Promise name. In particular, when we use Async / Await in TypeScript, the compiler converts this to Promise in the emitted code, so the compiler tries to protect the Promise constructor from being overwritten. You can always fool the compiler with these kinds of things, but be sure to ask yourself if this is the right thing to do.

+1
source

All Articles