Home > database >  React useState with typescript
React useState with typescript

Time:11-03

I have this code

interface AccountData {
  country: number |null;
}
const [accountData, setAccountData] = useState<AccountData>({ country:null });

Until we assign a value to a country it can be an undefined, null, or empty string.

Then I set the country value like this

const handleChange = (e: number) => {
  if(!isNaN(e)) {
    setAccountData({ country: e });
  }
};

And then I try to pass the value of the country to a function that requires the parameter as a number, I got this error

<Button
  small
  onClick={() => { handleSubmit(accountData.country); }}
>
  save
</Button>

Type 'null' is not assignable to type 'number'.

Which make sense typescript assumes this can be null sometimes. So I check if this is a number before I pass to the function like this

onClick={() => {
  if(!isNaN(accountData.country)) {
    handleSubmit(accountData.country);
  }
}}

But the error is still there. How can I fix this?

CodePudding user response:

Without seeing your handleSubmit function, I'm guessing it's annotated with number. There is a chance country can be null when this is submitted. Therefore TypeScript isn't happy with this.

Something like this might help:

const handleSubmit = (input: number | null) => {
  // stuff
}

CodePudding user response:

You can use as keyword to specify type number for country.

<Button
 small
 onClick={() => {
 handleSubmit(accountData.country as number);
}}>save</Button>

Refer: Type Narrowing

CodePudding user response:

If Counrt your value undefined, null, or empty string so can define also any. Which can accept undefined, null, or empty.

Learn more about typescript

interface AccountData {
    country: number | null | any;
}

const [accountData, setAccountData] = useState<AccountData>({ country:null });

const handleSubmit = (input: number | null | any) => {
   // do some stuff here
}
  • Related