我得到的一些数据中有一个元数据字段,我想将其删除。它出现在我这样的类型变量中:
type MainRecord = {
id: string
fieldOne: string
related: RelatedRecord[]
__typename: string
}
type RelatedRecord = {
id: string
fieldTwo: string
__typename: string
}
我正在使用Formik更新记录,但在创建表单的初始值时我不希望包含__typename
字段,因为尝试将包含元数据的数据发送到服务器会导致语法我这样做时查询的错误。我为Formik表单有单独的类型,如下所示:
type MainFields = {
id: string
fieldOne: string
related: RelatedFields[]
}
type RelatedFields = {
id: string
fieldTwo: string
}
我的解决方案是尝试将MainRecord
数据转换为MainFields
对象,这似乎是可行的,因为fields.__typename
不是有效的属性,fields.related[0].__typename
也不是。
const record: MainRecord = {
id: "10",
fieldOne: "Foo",
__typename: "Main",
related: [
{
id: "20",
fieldTwo: "Bar",
__typename: "Related"
},
{
id: "21",
fieldTwo: "Baz",
__typename: "Related"
},
]
}
const fields: MainFields = record // or "as MainFields"
但是,当您登录fields
变量时,元数据仍然存在并且不应该存在。
console.log("fields: ", fields);
我想我可以手工编程去除它们,但是必须有一种更好的方法。有任何想法吗?我敢肯定有一种打字稿的方式可以做到这一点,但我只是不知道。
答案 0 :(得分:1)
我认为TypeScript实际上不会在您使用as
关键字时发生突变,而只会以“如果您这样说”的方式将其“视为”适当的类型。
您最好的选择实际上是使用自己的实用程序或类似于lodash的属性对属性进行过滤。
Removing object properties with Lodash
看到这个似乎正在考虑类似问题的问题。
Remove properties from an object that are not declared in a type interface
答案 1 :(得分:0)
使用lodash的omit
函数,我找到了一种执行递归omit
的方法,如下所示:
function omitDeep(obj: any, keyToOmit: string) {
_.forIn(obj, function (value, key) {
if (_.isObject(value)) {
omitDeep(value, keyToOmit);
} else if (key === keyToOmit) {
delete obj[key];
}
});
}
```js