(TypeScript) Why can't I setState with an object containing the keys of my state type
See original GitHub issueWhy doesn’t this work:
export interface IState {
username: string;
password: string;
}
// ...
private onInputChange(e: Event, field: keyof IState) {
const target = e.target as HTMLInputElement;
this.setState({ [field]: target.value });
}
Am I incorrect in thinking this should work? field
is by definition one of the keys of IState
, so defining an object containing only field
as keys should be a valid IState
object. Is there an issue with the preact type declarations, or have I misunderstood something?
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (4 by maintainers)
Top Results From Across the Web
i can't setState with dynamic key name in typescript
The problem is that e.target.name should be key of IState and e.target.value should be relative type from key in IState , to fix...
Read more >Updating Arrays in State - React Docs
Just like with objects, when you want to update an array stored in state, you need to create a new one (or make...
Read more >React with Typescript - DEV Community
A few things about your React and TS usages, first React: Ideally you should avoid having objects for state, and use one state...
Read more >ReactJS setState() - GeeksforGeeks
setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value...
Read more >React & TypeScript: use generics to improve your types
TypeScript generics in React are very useful, but can be scary when you don't know how they work. This article will help you...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This seems to be cause as it did not match
Pick<State, keyof State>
, so it was trying to match explicitly withState
, when it should have beenPartial<State>
.Interesting. I think I played around with using
Partial
and it had some other side effects that I didn’t like, also, the React typings don’t usePartial
for setState butPick
like ours do. Will investigate. Related typing in react