'Assigning a name to an anonymous function (.name vs .displayName)
I am running a react native project, where this function
const f = function() {};
has an undefined name, not inferred.
Keeping the anonymous definition, is this code:
f.name = "f";
console.log(f.name); // f
an anti-pattern? Should I use .displayName instead?
Update (real code, the described one is a simpler version):
const MyComponent = forwardRef(({ userId }, ref) => {
useTrackScreenView(MyComponent.name, {
user_id: userId,
});
return JSX...
});
console.log(MyComponent.name) // undefined
//
// MyComponent.name = "MyComponent"; anti-pattern?
// or
// MyComponent.displayName = "MyComponent";
//
Solution 1:[1]
Using the @ts-check directive indicates that the Function's .name property is read-only.
So, the way to go is using .displayName.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Victorio Molina |
