Home > Blockchain >  Update Javascript code to Typescript to fix implicitly error
Update Javascript code to Typescript to fix implicitly error

Time:04-19

I'm working on my first react (Typescript) project and there is an issue with my code below.

I'm getting this error - Parameter 'name' implicitly has an 'any' type.ts(7006)

Bellow is my full code

export default function App() {
  const CHARACTER_LIMIT = 20;
  const [values, setValues] = React.useState({
    name: "Hello"
  });

  const handleChange = name => event => {
    setValues({ ...values, [name]: event.target.value });
  };

  return (
    <div className="App">
      <h1>Text Field with character limit</h1>
      <TextField
        label="Limit"
        inputProps={{
          maxlength: CHARACTER_LIMIT
        }}
        value={values.name}
        helperText={`${values.name.length}/${CHARACTER_LIMIT}`}
        onChange={handleChange("name")}
        margin="normal"
        variant="outlined"
      />
    </div>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

How can I fix this so that works without me needing to set "noImplicitAny": false

CodePudding user response:

You should give both name and event an explicit type:

const handleChange = (name: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
  setValues({ ...values, [name]: event.target.value });
};

CodePudding user response:

Add a type annotation to the nameparameter of your arrow function:

const handleChange = (name: string) => event => {
  setValues({ ...values, [name]: event.target.value });
};
  • Related