【问题标题】:Is there a way to remove all occurrences of the "__typename" property in Typescript?有没有办法删除 Typescript 中所有出现的“__typename”属性?
【发布时间】:2022-02-18 06:49:00
【问题描述】:

我想从字典“数据”中删除所有出现的“__typename”。我使用了这个stackoverflow帖子中的一个函数:How to remove all instances of a specific key in an object?,它输出了正确的答案,但我的编译器显示this error message。我是 Typescript 的新手,我很难找到解决方案。


代码 sn-p

import * as R from ramda;

// Dictionary "data"
const data = {
    "subscription": {
        "id": "10",
        "subscribers": [
            {
                "id": "2017",
                "username": "potato1",
                "__typename": "UserType"
            },
        ],
        "unsubscribers": [
            {
                "id": "2022",
                "username": "potato2",
                "__typename": "UserType"
            }
        ],
        "__typename": "SubscriptionType"
    },
    "__typename": "Subscribe"
};

// Function from linked stackoverflow post, works but get a syntax error (see screenshot)
const removePropDeep = R.curry((prop, data) =>
    R.when(
        R.is(Object),
        R.pipe(R.dissoc(prop), R.map(removePropDeep(prop))),
        data
    )
);

console.log(removePropDeep("__typename", data));

预期

{
    "subscription": {
        "id": "10",
        "subscribers": [
            {
                "id": "2017",
                "username": "potato1",
            },
        ],
        "unsubscribers": [
            {
                "id": "2022",
                "username": "potato2",
            }
        ],
    },
};

错误信息:

"Function implicitly has return type 'any'
because it does not have a return type annotation
and is referenced directly or indirectly
in one of its return expressions."

【问题讨论】:

标签: typescript ramda.js


【解决方案1】:

您需要使用接口创建函数重载定义,因为该函数是柯里化的。我使用了与R.dissoc (sandbox) 相同的定义。

注意:我已将 R.map 替换为 R.mapObjIndexed,因为 TS 很难推断在这种情况下 R.map 会迭代一个对象。

interface iRemovePropDeep {
  <T extends object, K extends keyof T>(prop: K, obj: T): Omit<T, K>;
  <K extends string | number>(prop: K): <T extends object>(
    obj: T
  ) => Omit<T, K>;
}

const removePropDeep: iRemovePropDeep = curry((prop, data) =>
  when(
    is(Object),
    pipe(dissoc(prop), mapObjIndexed(removePropDeep(prop))),
    data
  )
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2010-11-23
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多