打字稿 - 迭代以解析/完善对象
我正在尝试解析一个对象来完善不必要的数据 - 在这种情况下,我会在rtn [key]
上遇到错误,而我对为什么不了解。请阅读TL; dr的更多背景,并提前感谢;
type TValueCar = { make: { value: string }; model: { value: string } };
type TCarKey = keyof TValueCar;
type TCar = { make: { value: string }; model: { value: string } };
const parseCarValueObject = (valueObject: TValueCar): TCar => {
const ObjectKeys = Object.keys(valueObject) as TCarKey[];
const rtn = {} as TCar;
ObjectKeys.forEach((key) => {
rtn[key] = valueObject[key].value;
});
return rtn;
};
tl; dr 我希望创建此功能的通用版本,这是我尝试的第一阶段。我意识到,解决此问题的方法更简单,这并不是很简单,但对我创建通用功能没有帮助。 [下面的摘录]
const rtn = {
make:valueObject.make.value,
model:valueObject.model.value
}
I am trying to parse an object to refine the unnecessary data - in this case I get an error at rtn[key]
, and I have no understanding of why. Please read the tl;dr for some more context and thanks in advance;
type TValueCar = { make: { value: string }; model: { value: string } };
type TCarKey = keyof TValueCar;
type TCar = { make: { value: string }; model: { value: string } };
const parseCarValueObject = (valueObject: TValueCar): TCar => {
const ObjectKeys = Object.keys(valueObject) as TCarKey[];
const rtn = {} as TCar;
ObjectKeys.forEach((key) => {
rtn[key] = valueObject[key].value;
});
return rtn;
};
tl;dr
I am hoping to create a generic version of this function, and this is the first stage in my attempt. I realise that there is an easier way of solving this which doesn't would be very simple but wouldn't be helpful in my attempt to create the generic function. [Extract below]
const rtn = {
make:valueObject.make.value,
model:valueObject.model.value
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此行中,
您正在尝试将
valueObject
的值字符串分配给type tcar
,该期望类型的对象{value> {value:“ sosited” sometss'} ,这就是为什么您会遇到此错误的原因。
尝试简单地删除对
value
的访问,以便将整个对象分配给您的rtn
变量。See the example on typescript playground
In this line
You are trying to assign the string of value from
valueObject
to thetype TCar
that expects an object of type{ value: "something" }
, this is why you're getting this error.try to simply remove the access to
value
in order to assign the whole object to yourrtn
variable.See the example on typescript playground