带有async / await,Promise和函数默认参数的Typescript

时间:2017-07-21 08:37:43

标签: node.js typescript

我有一个nodeJS-Express-Typescript项目,我希望在async / await中使用一些本机promises,并为函数设置一些默认值。这将是我能够实现的一个简单例子:

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

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

    await sleep(500);

    doSomeMoreStuff();
}

IDE警告我这个错误:

$ 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.

所以我必须在我的tsconfig.json中添加es2015作为目标:

"target": "es2015"

但是,执行转换后的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)

因此我必须将目标更改为&#34; es5&#34;:

"target": "es5"

这会导致恶性循环。

我试过改变&#34; target&#34;的价值。和&#34;模块&#34;它总是失败的。

我在这里遗漏了什么吗?从理论上讲,打字稿2.2支持这两个功能,所以我不知道为什么我不能解释。

tsconfig.json

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

打字稿 2.4.1

节点 4.4.7

1 个答案:

答案 0 :(得分:3)

尝试使用tsconfig.json中的es2015.promise添加lib部分

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

您可以在此处查看完整示例:https://github.com/basarat/typescript-book/tree/master/code/async-await/es5