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
JavaScript
x
30
30
1
export default function App() {
2
const CHARACTER_LIMIT = 20;
3
const [values, setValues] = React.useState({
4
name: "Hello"
5
});
6
7
const handleChange = name => event => {
8
setValues({ values, [name]: event.target.value });
9
};
10
11
return (
12
<div className="App">
13
<h1>Text Field with character limit</h1>
14
<TextField
15
label="Limit"
16
inputProps={{
17
maxlength: CHARACTER_LIMIT
18
}}
19
value={values.name}
20
helperText={`${values.name.length}/${CHARACTER_LIMIT}`}
21
onChange={handleChange("name")}
22
margin="normal"
23
variant="outlined"
24
/>
25
</div>
26
);
27
}
28
const rootElement = document.getElementById("root");
29
ReactDOM.render(<App />, rootElement);
30
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:
JavaScript
1
4
1
const handleChange = (name: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
2
setValues({ values, [name]: event.target.value });
3
};
4