Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript (ReactJS) compiler error, this implicitly has type any

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?

like image 266
marchello Avatar asked Dec 14 '17 15:12

marchello


2 Answers

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 })
like image 180
meziantou Avatar answered Oct 22 '22 20:10

meziantou


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

 "noImplicitThis": false,               

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

like image 2
neelesh bisht Avatar answered Oct 22 '22 20:10

neelesh bisht