With this code:
else if (event.target.id == 'filter') {
this.setState({ [event.target.id]: event.target.value });
I get this typescript error: TS2345 TypeScript (TS) Argument of type '{ [x: number]: any; }' is not assignable to parameter of type '{ id: number; redirect: boolean; filter: string; player: Player; } | ((prevState: Reado...'.' …
But if I instead do this:
else if (event.target.id == 'filter') {
this.setState({ filter: event.target.value });
there's no error. Despite the error, the code runs fine. I think this started with TypeScript 2.9. I realize I can just use the second example, but I have other code like:
handleChange(event) {
if (event.target.type == 'checkbox') {
this.setState({ [event.target.id]: event.target.checked });
} else {
this.setState({ [event.target.id]: event.target.value });
}
}
which is useful. Is there a better way to do this in TypeScript 2.9?
Update: also relevant:
type PlayerListState = {
id: number,
redirect: boolean,
filter: string,
player: GamePlayer
};
class PlayerListComponent extends React.Component<PlayerListProps, PlayerListState> {
and the type definition of SetState from React:
setState<K extends keyof S>(
state: ((prevState: Readonly<S>, props: P) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),
callback?: () => void
): void;
id
anumber
? How would it equal the string"filter"
? – jcalzArgument of type '{[x: number]: any;}...
, it implies that TypeScript thinksevent.target.id
is anumber
. Are you sure about that error message? – jcalz