how to use es6-promises with typescript?

dcsan picture dcsan · Sep 5, 2015 · Viewed 53.6k times · Source

I read this SO question but having trouble getting promises to work with typescript. Hopefully we can make a clear guide. This is for a server/node project. I'm actually using latest iojs, but targeting ES5 as output.

$ tsd query es6-promise --action install --save
$ npm install --save es6-promise


// typescript code:

/// <reference path="../../typings/es6-promise/es6-promise.d.ts"/>

var Promise = require("es6-promise").Promise;
require('es6-promise').polyfill();

function test():Promise {
    var p:Promise = new Promise();
    return p;
}

this is giving the error:

Cannot find name 'Promise'.

// alternatively:

var p = new Promise<string>((resolve, reject) => {
    resolve('a string');
});


//error=> Untyped function calls may not accept type arguments.

What is the recommended way to return a Promise from your own node server side code?

references:

Answer

Ilya Kharlamov picture Ilya Kharlamov · Sep 5, 2015

main.ts

import {Promise} from 'es6-promise';
const p: Promise<string> = new Promise (
   (resolve: (str: string)=>void, reject: (str: string)=>void) => {
      const a: string = "hello from Promise";
      resolve(a);
   }
 );
p.then((st) => {
  console.log(st);
});

tsconfig.json

{
    "compilerOptions": {
        "target": "es3",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "noLib": false
    },
    "filesGlob": [
        "./**/*.ts",
        "!./node_modules/**/*.ts"
    ],
    "files": [
        "./main.ts",
        "./typings/es6-promise/es6-promise.d.ts"
    ]
}

compileandrun.sh

#!/bin/sh
npm install es6-promise
tsd install es6-promise
tsc
node main.js