8
votes

I have a React component written in TypeScript:

class App extends React.Component<props> {

  constructor(props) {
    super(props);
    this.treeNavElement = this.treeNavElement.bind(this);
  }

  treeNavElement() {
    return (
      <div></div>
    )
  }

  render() {
    return (
      <div>
        {
          this.props.NavDataTree.map(function(elem) {
            return <div key={elem.id} onClick={this.treeNavElement}>{elem.name}</div>
          }, this)
        }
      </div>
    )
  }
}

export default App;

My problem is that the typescript compiler yells at me, because of this line:

return <div key={elem.id} onClick={this.treeNavElement}>{elem.name}</div>

Saying:

[ts] 'this' implicitly has type 'any' because it does not have a type annotation.

Outside of map function, in map's second parameter and this.props it works fine, but inside onClick this is lost.

If I set "noImplicitThis": false in tsconfig.json it is fine, but I would like to know if there is a way around this without turning implicitthis off?

2
What if you use an arrow function? - Explosion Pills
It is the same. - marchello
What @Explosino Pills means is ...map((elem) => { ... }) - unional
I know what he means, that doesn't change a thing about that this is unknown at compile time inside map. Again: this is a compile time issue, nuking this with any and zero issues at runtime. - marchello
Sorry, that is working for this, but now it has a different error. - marchello

2 Answers

2
votes

You use a function, so this is lost.

this.props.NavDataTree.map(function(elem) { })

You can type this if you know what this is at runtime function(this: XXX) {}. Or you can use the arrow operator, so this is propagate into the function

this.props.NavDataTree.map(elem => { this.XXX })
1
votes

Here's a quick fix, add the following line to tsconfig.js.

 "noImplicitThis": false,               

Raise error on 'this' expressions with an implied 'any' type.