简体   繁体   中英

Property 'previous' is missing in type - TypeScript + ReactJS

Quite new to reactjs and 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

interface

interface IPropertyTax {
  annul: {
    current: number;
    previous: number;
  };
  monthly: {
    current: number;
    previous: number;
    difference: number
  };
}

useState

    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; }'

I know it's because I didn't add previous since in my interface it's a required field.

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)

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

const newPropertyTax = propertyTax;
newPropertyTax?.annual?.current = validatedValue;
setPropertyTax(newPropertyTax);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM