Skip to content
Advertisement

Update Javascript code to Typescript to fix implicitly error

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

Advertisement

Answer

You should give both name and event an explicit type:

const handleChange = (name: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
  setValues({ ...values, [name]: event.target.value });
};
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement