8

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?

5
  • 1
    What if you use an arrow function? Commented Dec 14, 2017 at 15:52
  • It is the same. Commented Dec 14, 2017 at 15:59
  • What @Explosino Pills means is ...map((elem) => { ... }) Commented Dec 14, 2017 at 16:04
  • 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. Commented Dec 15, 2017 at 9:43
  • Sorry, that is working for this, but now it has a different error. Commented Dec 15, 2017 at 9:54

2 Answers 2

2

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

1 Comment

This is completely a compile time issue. If I suppress it with noImplicitAny, I have no runtime issues. I don't think this is lost. It would be in the callback function body, because of the this-binding rules, but inside render() it should be available because I specifically supplied this to the thisArg parameter of map. From mozilla docs: thisArg Value to use as this when executing callback. So this should be available at compile time inside map.
2

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

 "noImplicitThis": false,               

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.