【问题标题】:Typescript with async/await, Promise and function default parameters带有 async/await、Promise 和函数默认参数的打字稿
【发布时间】:2017-07-21 08:37:42
【问题描述】:

我有一个 nodeJS-Express-Typescript 项目,我想在其中使用一些带有 async/await 的原生 Promise 以及一些函数的默认值。这将是我可以实现的一个简单示例:

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)

所以我必须将目标更改为“es5”:

"target": "es5"

这会导致恶性循环。

我试过改变“target”和“module”的值,但总是失败。

我在这里遗漏了什么吗?理论上,typescript 2.2 支持这两个功能,所以我不明白为什么我不能转译。

tsconfig.json

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

打字稿 2.4.1

节点 4.4.7

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    尝试在 tsconfig.json 中添加带有 es2015.promise 的 lib 部分

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

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

    【讨论】:

    • 您好,感谢您的回答。添加这些之后,它会在每一行中向我抛出这个错误error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. 有一个 for-of 循​​环。
    • 添加 "es2015" ,然后您将添加完整的 es2015 功能集
    • Nothing... 同样的错误 Unexpected token = 如果你想自己试一试,代码就在这里:/ github.com/josemigallas/users-api/tree/async_await_es5
    猜你喜欢
    • 2017-08-26
    • 2019-11-18
    • 2020-09-22
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2016-04-14
    相关资源
    最近更新 更多