Search code examples
typescriptes6-promise

ES6 Promise requires argument in typescript 2.0?


I am continuing work on an existing typescript project. The original project used gulp-typescript to compile the .ts files, but I am using the tsc compiler that comes with Visual Studio Code. But I can't get ES6 promises to work.

I have installed a definition file for ES6 promises:

npm install --save @types/es6-promise

This creates a directory inside the node_modules folder that has the promise definition file:

node_modules
    @types
        es6-promise
            index.d.ts
            package.json
            types-metadata.json
            readme.md

tsconfig.json

"files": [
    "src/main.ts",
    "src/game.ts",
    "node_modules/@types/es6-promise/index.d.ts"
]

reference

///<reference path="../node_modules/@types/es6-promise/index.d.ts" />

I'm assuming that including the promise definition file is now working, but I get the following error when compiling the project:

error TS2314: Generic type 'Promise<T>' requires 1 type argument(s).

When I look in the original code I find this:

    private componentsPromise: Promise<Component[]>;
    private startPromise: Promise; // <- error

    public getComponents(): Promise<Component[]> {
        return this.componentsPromise;
    }

    public isStarted(): Promise {   // <-- error
        return this.startPromise;
    }

Is this a simple error in the original project or am I missing something? What do I need to add here to get promises working again?


Solution

  • A promise is generic because it varies on its internal value. So if you have a promise and you call .then(x => ...), what is the type of x? The generic allows the type checker to interpret this correctly.

    To get this working, you need to add the specific type. If it contains no data and is being used purely for the resolve/reject functionality, use Promise<void>. Ultimately this is a type signature like any other, so you can use Promise<any> if you need to.