[英]Property 'previous' is missing in type - TypeScript + ReactJS
Quite new to reactjs and ts. reactjs 和 ts 很新。 I know why I am having this error, but I am not sure what would be the best fix for this
我知道为什么会出现这个错误,但我不确定什么是最好的解决方法
Currently using reactjs
created an目前使用
reactjs
创建了一个
interface IPropertyTax {
annul: {
current: number;
previous: number;
};
monthly: {
current: number;
previous: number;
difference: number
};
}
const [propertyTax, setPropertyTax] = useState<IPropertyTax>({
annul: {
current: 0,
previous: 0
},
monthly: {
current: 0,
previous: 0,
difference: 0
}
});
this action will be done trying to set the state此操作将尝试设置状态
setPropertyTax({
...propertyTax,
annul: { current: validatedValue },
monthly: { current: monthlyPropertyTax }
});
Then I would get an error of Property 'previous' is missing in type '{ current: number; }' but required in type '{ current: number; previous: number; }'
然后我会得到一个错误,
Property 'previous' is missing in type '{ current: number; }' but required in type '{ current: number; previous: number; }'
Property 'previous' is missing in type '{ current: number; }' but required in type '{ current: number; previous: number; }'
I know it's because I didn't add previous
since in my interface it's a required field.我知道这是因为我没有添加
previous
的内容,因为在我的界面中它是必填字段。
So I thought maybe I should make them options such as所以我想也许我应该让他们选择,比如
interface IPropertyTax {
annul: {
current?: number;
previous?: number;
};
monthly: {
current?: number;
previous?: number;
difference?: number
};
}
but this would lead to propertyTax.monthly.current
might be Object is possibly 'undefined'
which I could just do (propertyTax.monthly.current || 0)
但这会导致
propertyTax.monthly.current
可能是Object is possibly 'undefined'
,我可以这样做(propertyTax.monthly.current || 0)
The above would work, but I didn't know if that's the a good option?以上可行,但我不知道这是否是一个好的选择?
I thought of another way might be我想到了另一种方法可能是
setPropertyTax({
...propertyTax,
annul: { current: validatedValue, previous: propertyTax.annul.previous },
monthly: { current: monthlyPropertyTax, previous: propertyTax.monthly.previous, difference: propertyTax.monthly.difference }
});
But again, any of these are good options?但同样,这些都是不错的选择吗? or there is a better way to work this out?
还是有更好的方法来解决这个问题?
Thanks in advance for any help.提前感谢您的帮助。
As u are not setting few properties, u are getting this error.由于您没有设置一些属性,因此您收到此错误。
if u are trying to update the annual.current property then u can do like this如果你正在尝试更新 year.current 属性,那么你可以这样做
const newPropertyTax = propertyTax;
newPropertyTax?.annual?.current = validatedValue;
setPropertyTax(newPropertyTax);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.