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?
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 })
Here's a quick fix, add the following line to tsconfig.js.
"noImplicitThis": false,
Raise error on 'this' expressions with an implied 'any' type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With