【问题标题】:Rename object keys of return object [duplicate]重命名返回对象的对象键[重复]
【发布时间】:2021-05-05 06:07:51
【问题描述】:

情景

一个方法matter返回一个对象,比如return {content, data}

冲突

方法的第二次调用(来自节点模块的方法)会覆盖之前从返回中设置的变量。

import matter from 'gray-matter'

const test = () => {
...
   const { content, data } = matter(source1)
   const { content, data } = matter(source2) // this overwrites previous content, data vars
...
}

目标/问题

在不同的命名变量中设置返回值,例如:

const { content2, data2 } = matter(source2) // like so it leads to an compiling error property content2 does not exists on type [...]

那么,如何将返回值分配给类型中命名的不同命名变量?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    只需使用不同的变量名:

    const { content, data } = matter(source1)
    const { content: content2, data: data2 } = matter(source2)
    

    或者根本不解构:

    const result1 = matter(source1)
    const result2 = matter(source2)
    

    或者使用对象数组:

    const results = [source1, source2].map(matter);
    

    【讨论】:

    • 非常感谢您的回答。它有效。
    猜你喜欢
    • 2020-10-14
    • 2016-09-04
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多