3

I have TypeScript in my React app.

I use computed keys in order to update component's state.

    const {name, value} = ev.target;
    this.setState({
      [name]: value
    })

But TS throws an error:

Error:(25, 19) TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'State | ((prevState: Readonly, props: Readonly<{}>) => State | Pick | null) | Pick | null'. Type '{ [x: string]: string; }' is missing the following properties from type 'Pick': from, to

I understand why it trows. I don't know how to fix it. How to tell TS that computed keys are either from or to?


// State interface
// Only two keys, 'from' and 'to'
interface State {
  from: string,
  to: string,
  // [key: string]: string // <= a quick solution, but it's very generic I guess
}

  // 'name' can be either 'from' or 'to'
  // So I use computed keys to set state's key
  onDirectionSelect = (ev: React.ChangeEvent<HTMLSelectElement>) => {
    const {name, value} = ev.target;
    this.setState({
      [name]: value // <= TS blows up here
    })
  };
Green
  • 28,742
  • 61
  • 158
  • 247
  • https://stackoverflow.com/questions/44110641/typescript-a-computed-property-name-in-a-type-literal-must-directly-refer-to-a-b – Jayce444 Sep 06 '19 at 01:15

0 Answers0