0

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>
    )
  }

1 Answer 1

1

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>
    )
  }
Sign up to request clarification or add additional context in comments.

5 Comments

So can one not define an array within render/return here then?
Added "solution to declaring"
@Greg, you technically can but it's generally not recommended. What is it exactly that you're trying to accomplish?
ok - got confused I think - thought I could do this in jsx but now it was not working in tsx - so basically then need to declare outside the "return" section of the render method I assume of a react component
@Greg, yes, all data structures should be initialized and set up before so you can just plug them in when rendering the JSX. There is a very ugly and performance-destroying workaround if you desperately need it

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.