5

Similar but distinct from How do I dynamically assign properties to an object in TypeScript?

I have a component with the state type:

{
  low: string
  high: string
}

And as is a common pattern in React, my event handler is:

handleChange = (e) => {
  let { name, value } = e.target;
  this.setState({ [name]: value });
};

With high and low as name attributes on my inputs. Typescript is erroring with:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Pick<State, "low" | "high">'

Is there a way for me to tell Typescript that I only expect those 2 values? I'd like to avoid explicitly passing the key into the handler but don't want to change the state to something like:

{
  low: string
  high: string
  [key: string]: string
}

1 Answer 1

15

In the perfect world we should be able to write something like this:

private handleChange = (e: {target: {name: "low" | "high", value: string}}) =>
{
    const { name, value } = e.target;

    this.setState({[name]: value});
}

But unfortunately a reported bug (see here or here) force us to use some temp workaround like casting to any or such:

this.setState({[name]: value} as any);
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, thanks for the issue links and workaround. as any should work fine here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.