Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useState Props: Type 'string' is not assignable to type 'number'. TS2322

I am trying pass to Props to React useState Hooks. Both my props are required and number but I am getting Typescript error that:

Type 'string' is not assignable to type 'number'. TS2322

But I am not passing anywhere the string. So, I don't know why I am getting this Typescript. I don't want to pass props any.

import React, { useState } from "react";
import ReactDOM from "react-dom";

interface Props {
  strength: number;
  speed: number;
}

const Courseinfo = ({ strength, speed }: Props) => (
  <>
    <div>
      <h1>{strength}</h1>
      <h1>{speed}</h1>
    </div>
  </>
);

const App = () => {
  const [character, setCharacter] = useState<Props>({ // This Props throws me error 
    strength: 0,
    speed: 0,
  });

  const { strength, speed } = character;
  return (
    <>
      Strength:
      <input
        type="number"
        value={strength}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
          setCharacter({ ...character, strength: e.target.value })
        }
      />
      Speed:
      <input
        type="number"
        value={speed}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
          setCharacter({ ...character, speed: e.target.value })
        }
      />
      <Courseinfo strength={strength} speed={speed} />
    </>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
like image 851
Krisna Avatar asked Nov 02 '25 21:11

Krisna


1 Answers

input type="number"'s value is a string

Here's the fixed sandbox.

Changes:

interface Props {
  strength: string;
  speed: string;
}

and event's type can be

onChange={(e: React.ChangeEvent<HTMLInputElement>) =>

Alternately you can also convert event.target.value to a number(+event.target.number) instead of changing the prop types.

like image 139
Ramesh Reddy Avatar answered Nov 05 '25 16:11

Ramesh Reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!