简体   繁体   中英

type="number" react typescript false positive in onChange?

I got error in line 24

Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345)

using typescript for a react experiment.

const App: React.FC = () => {
  const [name, setName] = React.useState<string>(null);
  const [tel, setTel] = React.useState<number | undefined>(null);

  return (
    <div>
      <input
        value={name}
        type="text"
        placeholder="name"
        onChange={e => setName(e.target.value)}
      />
      <input
        value={tel}
        type="number"
        placeholder="tel."
        onChange={e => setTel(e.target.value)} // here?
      />
    </div>
  );
};

https://codesandbox.io/s/silly-moore-wve1p

It doesn't happens with type="text" I've already specify the type, it's strange.

As I mentioned in the comments adding the parseInt() to change the string type number from the event into a number will match the type you set for that useState

I also changed the initial values of the useState's to match their defined types.

  const App: React.FC = () => {
  const [name, setName] = React.useState<string>('');
  const [tel, setTel] = React.useState<number | undefined>(undefined);

  return (
    <div>
      <input
        value={name}
        type="text"
        placeholder="name"
        onChange={e => setName(e.target.value)}
      />
      <input
        value={tel}
        type="number"
        placeholder="tel."
        onChange={e => setTel(parseInt(e.target.value))}
// setTel('12312')<string>  => setTel(parseInt('12312'))<number>
      />
    </div>
  );
};

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