Search code examples
reactjstypescripttsx

Declaring array in react typescript tsx file gives "error TS1109: Expression expected"


When I try to declare an array within a React (but using typescript) tsx file I get the error message:

"error TS1109: Expression expected"

  public render() {
    return (
      <div>
        {  var nums:number[] = [1,2,3,3]  }  // ERROR HERE
      </div>
    )
  }

Solution

  • Your code var nums:number[] = [1,2,3,3] is not an expression. It's a statement.

    An expression would be [1,2,3,3].

    Easy way to think about it

    Anything that can be assigned to a variable is an expression. You wouldn't do:

    const foo = var nums:number[] = [1,2,3,3]; // ERROR `var nums:number[] = [1,2,3,3]` is not an expression
    

    Solution to declaring

    Do it out of JSX e.g.

    public render() {
        var nums:number[] = [1,2,3,3]
        return (
          <div>
            {  nums[0]  }
          </div>
        )
      }