Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript with async/await, Promise and function default parameters

I have a nodeJS-Express-Typescript project where I want to use some native promises with async/await and also some default value for a function. This would be a simple example of what I can achieve:

sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, 500));
}

async someFunction(param = "default") {
    doStuff(param);

    await sleep(500);

    doSomeMoreStuff();
}

The IDE warns me about this error:

$ tsc -p .

error TS2468: Cannot find global value 'Promise'.
spec/routes/users.spec.ts(508,23): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
src/utils/sleep.ts(10,20): error TS2693: 'Promise' only refers to a type, but is being used as a value here.

so I have to add es2015 as target in my tsconfig.json:

"target": "es2015"

But then, this error comes when executing the transpiled JS:

/../users-api/dist/src/repository/realm-helper.js:21
    static init(development = false) {
                            ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/../users-api/dist/src/routes/users.js:4:24)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

So that I have to change the target to "es5":

"target": "es5"

Which leads to a vicious circle.

I've tried changing the value of "target" and "module" and it always fails something.

Am I missing something here? In theory, typescript 2.2 supports both features so I don't get why I can't transpile.

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "rootDir": ".",
        "sourceMap": true,
        "module": "commonjs",
        "target": "es5"
    },
    "include": [
        "./src/**/*",
        "./spec/**/*"
    ]
}

typescript 2.4.1

node 4.4.7

like image 945
josemigallas Avatar asked Sep 12 '26 15:09

josemigallas


1 Answers

Try Adding lib section with es2015.promise in tsconfig.json

    "lib": [
        "dom",
        "es5",
        "scripthost",
        "es2015.promise"
    ], 

You can see the full sample here: https://github.com/basarat/typescript-book/tree/master/code/async-await/es5

like image 167
José Quinto Zamora Avatar answered Sep 15 '26 10:09

José Quinto Zamora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!