【问题标题】:Typescript error:Object.fromEntries typescript Error打字稿错误:Object.fromEntries 打字稿错误
【发布时间】:2020-06-04 18:28:49
【问题描述】:

我在 typescript 中有一个函数,它使用 Object.fromEntries 来减少复杂的响应对象并使用子对象键的子字符串对其进行分组。

let Newresult = res.map(object => Object.fromEntries(Object.entries(object).map(([key, value]) => [
key,
value.map(valueobject => Object.entries(valueobject).reduce((res1, [name, value]) => {
    const key = name.slice(0, 5);
    res1[key] = res1[key] || {};
    res[key][name] = value;
    return res1;
}, {}))
])));

但问题是 typescript 在编译时抛出错误。

error TS2339: Property 'fromEntries' does not exist on type 'ObjectConstructor'.
error TS2339: Property 'map' does not exist on type '{}'.

我尝试将 ESNext,ES2017.Object 添加到我的 tsconfig.json 库数组中,但仍然抛出编译错误。 但我的 lib-array 的相同更新允许我使用 Object.entries。

我正在使用 angular -v-6,打字稿:~3.1.1

还有哪些方法可以帮助我达到与上述相同的结果。 有人能指引我正确的方向吗?

提前致谢!!

【问题讨论】:

    标签: angular typescript object


    【解决方案1】:
    • TypeScript 版本为 3.9

    打开 tsconfig.json

    添加

    "target": "esnext",
    "lib": ["esnext", "dom"]
    

    【讨论】:

    • 我遇到了同样的问题。我尝试将 lib 和 target 都设置为 esnext、es2019、es2020,但我不断收到关于 Object.fromEntries 的错误消息。 --- 属性“fromEntries”在“ObjectConstructor”类型上不存在。您需要更改目标库吗?尝试将 lib 编译器选项更改为 'es2019' 或更高版本
    【解决方案2】:

    Object.fromEntries 是 ES2019,因此您的 lib 选项需要包含它(或 ES2020)。 (ESNext 是一个移动的目标。)

    也就是说,TypeScript v3.1.1 已经相当老了。您可能需要升级。

    【讨论】:

    • 但是将 ES2019 添加到我的 lib 选项中会引发更多错误。截至目前,我的 tsconfig.json 目标设置为“es5”。
    • 这是一个现有的角码,升级打字稿不是一种选择。因此寻找替代@t-j-crowder
    • 好吧,TypeScript v3.1.1 是 released Sep 2018,所以我有点惊讶将 ESNext 添加到 libs 没有工作,因为 fromEntries 进入第 3 阶段还很远那一点。如果你真的要发布到 ES5 级别的浏览器,你当然需要一个 polyfill。
    猜你喜欢
    • 2018-06-05
    • 2020-08-01
    • 1970-01-01
    • 2019-01-24
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多