Reputation: 97
I have a tsx file with react-native. My function name is underlined if function is not set to const or let with this message:
Cannot find name 'goBack'
goBack = () => {
// do stuff
}
But it works if I set const or let:
const goBack = () => {
// do stuff
}
Why ?
Upvotes: 7
Views: 7831
Reputation: 1074385
This doesn't have anything to do with arrow functions. You're trying to assign a value to an identifier you haven't declared anywhere.
This:
goBack = () => {
// do stuff
}
assigns an arrow function to the already declared identifier goBack
. (Or, if this were within a class
, it would create a new property and assigns the arrow function to it — but we know you're not doing this in a class, beacuse your const
version would fail if you were.)
It's exactly like:
answer = 42;
If answer
isn't declared, you get an error from TypeScript.
This:
const goBack = () => {
// do stuff
}
creates a local variable (well, constant) and assigns the arrow function to it, just like:
const answer = 42;
It's useful to remember that arrow functions have no declaration syntax. An arrow function is always an expression. The part to the left of the =
in your examples isn't part of that arrow function expression (although, somewhat surprisingly, it can have an effect on the function that's created).
Upvotes: 10