4

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"));
Krisna
  • 2,854
  • 2
  • 24
  • 66

1 Answers1

2

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.

Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32