0

I can't think of a way to destructure an object from provided argument:

type PossibleStateProperty = 'hello' | 'world'

type State = {
  hello: 'welcome',
  world: 'earth'
}

handleError = (name: PossibleStateProperty) => {
   const { [name] } = this.state
}

Where I would destructure the state object property based on the provided function argument.

const { [name] } = this.state

is sadly invalid

Samuel Hulla
  • 6,617
  • 7
  • 36
  • 70
  • Destructuring can only extract variables that exist in an object, i.e. `const { hello, world } = this.state;` – JDunken Jan 17 '20 at 18:14
  • Hi, can you clarify your example code? You are typing `name` param as `PossibleStateProperty` which is a string union type. If you want to destructure your state, follow @JDunken suggestion. – karlmarxlopez Jan 17 '20 at 18:15
  • 2
    `const { [name]: value } = this.state` where `value` will be the variable available in that scope. – Emile Bergeron Jan 17 '20 at 18:18
  • @EmileBergeron ooh yes, in the meantime I came up with `const value = this.state[name]` but I prefer your suggested destruct syntax. Thanks for linking to the other question :) – Samuel Hulla Jan 17 '20 at 22:27
  • Both are equally valid, I'd even say that destructuring is just overkill in this case, but most React app setup have the `prefer-destructuring` linting rule which prompts most dev to go with my suggestion above. – Emile Bergeron Jan 17 '20 at 22:33
  • I do agree it is an overkill, but I'm destructuring other more standard state properties (which I excluded in my example for clarity), so it feels more natural to do it in one statement. – Samuel Hulla Jan 17 '20 at 23:34

0 Answers0