TypeScript 承诺会引发编译时错误,但不会引发运行时错误

时间:2021-04-14 11:18:30

标签: javascript typescript promise

我有这个代码:

async function fetchApi(): Promise<IStoreApi | null> {
    try {
        return await (await fetch("http://www.json-generator.com/api/json/get/cfDcpslXnm?indent=2")).json();
    }
    catch(e: any) {
        return null;
    }
}

console.log(fetchApi);

它在 linting 时没有显示错误,但是在编译时,我收到以下错误:

index.ts(23,28): 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.
constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
index.ts(27,14): error TS1196: Catch clause variable cannot have a type annotation.

我试过在谷歌上搜索错误并提供一些建议我应该更改我的 tsconfig.json 文件的提示,但这没有帮助。
另外,我觉得奇怪的是我没有收到运行时错误,但我确实收到了编译时错误。

这是我的 tsconfig 文件:

{
    "compilerOptions": {
        "target": "ESNext",
        "module": "commonjs",
        "lib": [
            "es2015",
            "dom",
            "es2015.promise"
        ]
    }
}

谢谢

0 个答案:

没有答案