【问题标题】:Promise' only refers to a type, but is being used as a value herePromise' 仅指一种类型,但在这里用作值
【发布时间】:2019-07-30 18:50:05
【问题描述】:

有点想弄清楚异步的东西在打字稿中是如何工作的,当我运行我的编译器时,它会产生这个错误。这是我要编译的代码:

Printer.ts

export class Printer
{ 
    public static printString(string: string, callback): void
    {
        setTimeout(
            () => {
                console.log(string)
                callback()
            },
            Math.floor(Math.random() * 100) + 1
        )
    }

    public static printStringWithPromise(string: string): Promise<void>
    {
        return new Promise<void> ((resolve, reject) => {
            setTimeout(
                () => {
                    console.log(string)
                    resolve()
                },
                Math.floor(Math.random() * 100) + 1
            )
        })
    }
}

Main.ts

import { Printer } from './Printer';


class App
{
    public static run(): void
    {
        Printer.printStringWithPromise("A")
               .then(() => Printer.printStringWithPromise("B"))
               .then(() => Printer.printStringWithPromise("C"))
    }
}


App.run();

然后我只运行tsc src/Main.ts --outDir out/,它就会向我抛出上述错误。我做错了什么?

【问题讨论】:

  • 在您的 tsconfig compiler options 中,检查您的 --target 和/或 --libPromise constructor 仅适用于 ES2015 及更高版本。
  • @jcalz 好吧,是的,我必须添加 tsconfig 文件,我必须将 target 字段设置为 es6,然后可以使用 tsc --project PATH_TO_PROJECT --outDir PATH_TO_OUTDIR &amp;&amp; nodejs PATH_TO_OUTDIR/Main.js 编译和运行它我想知道是否可以不用tsconfig 并在命令行中设置所有必需的东西。
  • 你可以在命令行afaik上使用--target
  • @jcalz 是的,我现在明白了。它有效。
  • @jcalz:请作为答案发布。

标签: typescript


【解决方案1】:

在您的 tsconfig compiler options 中,检查您的 --target 和/或 --libPromise constructor 仅适用于 ES2015 及更高版本。祝你好运!

【讨论】:

    【解决方案2】:

    默认情况下,TypeScript 在编译期间仅包含 es3 库,但 Promise 仅包含 es6 (aka es2015)。因此,您必须将 es6 包含在 tsconfig.json#compilerOptions#lib 数组中 - 下面是最小示例。


    tsconfig.json

    {
      "compilerOptions": {
        "lib": ["es6"]
      },
      "files": ["index.ts"]
    }
    

    index.ts

    const prom = new Promise(resolve => resolve('hello world'));
    

    测试脚本

    npm i typescript
    tsc # <- should not throw any error
    

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 2019-10-08
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2018-12-30
      相关资源
      最近更新 更多