[javascript] How to use Typescript with native ES6 Promises

I'm a complete beginner to Typescript and am wondering if it's possible to use ES6 promises in Typescript and what I would have to do to get them to work. I'm running node 0.11.14 and am getting an error during compilation "Cannot find name 'Promise'"

This question is related to javascript typescript es6-promise

The answer is


As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

This will include the promise declarations that comes with TypeScript without having to set the target to ES6.


If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:

tsc a.ts --target es6 --module commonjs

More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options

If you use tsconfig.json, then like this:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6"
    }
}

More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json


Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2

No npm install required as ES6 Promises is native.

Node.js project -> Properties -> Typescript Build tab ECMAScript version = ECMAScript6

import http = require('http');
import fs = require('fs');

function findFolderAsync(directory : string): Promise<string> {

    let p = new Promise<string>(function (resolve, reject) {

        fs.stat(directory, function (err, stats) {

            //Check if error defined and the error code is "not exists"
            if (err && err.code === "ENOENT") {
                reject("Directory does not exist");
            }
            else {
                resolve("Directory exists");
            }
        });

    });
    return p;
}

findFolderAsync("myFolder").then(

    function (msg : string) {
        console.log("Promise resolved as " + msg); 
    },
    function (msg : string) {
        console.log("Promise rejected as " + msg); 
    }
);

A. If using "target": "es5" and TypeScript version below 2.0:

typings install es6-promise --save --global --source dt

B. If using "target": "es5" and TypeScript version 2.0 or higer:

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

C. If using "target": "es6", there's no need to do anything.


I had to downgrade @types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.

"@types/core-js": "0.9.36",


Alternative #1

Use the target and lib compiler options to compile directly to es5 without needing to install the es6-shim. (Tested with TypeScript 2.1.4). In the lib section, use either es2016 or es2015.promise.

// tsconfig.json
{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "es2015.promise",
            "dom"
        ]
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

Alternative #2

Use NPM to install the es6-shim from the types organization.

npm install @types/es6-shim --save-dev

Alternative #3

Before TypeScript 2.0, use typings to install the es6-shim globally from DefinitelyTyped.

npm install typings --global --save-dev
typings install dt~es6-shim --global --save-dev

The typings option uses npm to install typings globally and then uses typings to install the shim. The dt~ prefix means to download the shim from DefinitelyTyped. The --global option means that the shim's types will be available throughout the project.

See also

https://github.com/Microsoft/TypeScript/issues/7788 - Cannot find name 'Promise' & Cannot find name 'require'


This the most recent way to do this, the above answer is outdated:

typings install --global es6-promise


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to es6-promise

How to reject in async/await syntax? What is difference between Axios and Fetch? What is an unhandled promise rejection? JavaScript ES6 promise for loop Returning Promises from Vuex actions how to cancel/abort ajax request in axios Axios get access to response header fields How to pass parameter to a promise function Wait until all promises complete even if some rejected Handling errors in Promise.all