Search code examples
javascriptecmascript-6vuejs2webpack-2

[Vue warn]: "TypeError: Cannot read property 'type' of undefined?"


Could someone help me understand the behavior of the code below?:

wrapperProperties () {
  let properties = this.getToValueOf('wrapper', {})
  [properties['type'], properties['message']] = this.defineValidationState()
  return properties
}

I'm getting the following warning:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'type' of undefined"

When I add any variable between the let keyword and destructuring assignment the code completed successfully:

wrapperProperties () {
  let properties = this.getToValueOf('wrapper', {}), mysteriousVar
  [properties['type'], properties['message']] = this.defineValidationState()
  return properties
}

Why is this happening?


Solution

  • The problem is this:

    let properties = this.getToValueOf('wrapper', {})
    [properties['type'], properties['message']]
    

    Is interpreted as this:

    let properties = this.getToValueOf('wrapper', {})[properties['type'], properties['message']]
    

    So instead of destructuring it is interpreted as property access using the [] syntax.

    You should either insert semicolons at the end of every statement or you should really read and understand the standard.js coding standard. According to standard.js you must put a semicolon at the beginning of every line that starts with { or [.

    I personally prefere classic "Douglas Crockford" style so I'd add a semicolon at the end of every statement. But either way works:

    "Crockford" style:

    wrapperProperties () {
      let properties = this.getToValueOf('wrapper', {});
      [properties['type'], properties['message']] = this.defineValidationState();
      return properties;
    }
    

    Standard.js style:

    wrapperProperties () {
      let properties = this.getToValueOf('wrapper', {})
      ;[properties['type'], properties['message']] = this.defineValidationState()
      return properties
    }