setState has wrong type
See original GitHub issueWe have interface:
interface State {
condition: boolean;
left: number;
right: number;
}
and defined state:
public state: State = {
condition: true,
left: 0,
right: 0,
};
Consider method:
public change= (value: number) => {
this.setState((state) => {
if(state.condition) {
return {
left: value,
}
} else {
return {
right: value,
}
}
});
};
This cause an error during compilation.
TS:
...
Type '{ left: number; right?: undefined; }' is not assignable to type 'Pick<State, "left" | "right">'.
Types of property 'right' are incompatible.
Type 'undefined' is not assignable to type 'number'.
Posible Solution:
setState<K extends keyof S>(
state: ((prevState: Readonly<S>, props: Readonly<P>) => (Partial<Pick<S, K>> | S | null)) | (Pick<S, K> | S | null),
callback?: () => void
): void;
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (1 by maintainers)
Top Results From Across the Web
React .setState returns type error - Stack Overflow
The setState is a function, you change it to an JavaScript Object , I guess it's a tiny mistake, you have to write:...
Read more >Why is setState giving me the wrong value? - Codetain
The first one shows what user types in the input field. The second one indicates what will be sent from our form. Right...
Read more >React setState usage and gotchas - ITNEXT
A React class component has an internal state which like props affects how the component renders and behaves. Unlike props, state is local...
Read more >How To Use and Not Use State - React Training
You just can't conditionalize the calls to useState because the call order matters to React. The number of times you called useState is...
Read more >React.Component
These methods are called when there is an error during rendering, ... it should examine this.props and this.state and return one of the...
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
Im not sure, maybe I should add this issue to
DefinitelyTyped/DefinitelyTyped/tree/master/types/react
The React team doesn’t maintain these TypeScript definitions. Please file this issue in the
DefinitelyTyped
repo. Thanks!