Reputation: 2336
I have the following issue. We are importing functions as such:
import { selectView } from '../actions';
However when I declare the actual React component we have something like this:
const CompleteProfileModal = (props) => {
const { selectView } = props; // I want to prevent this declaration from being possible as it is a name collision, if I forgot this I would later call the imported function.
...
}
const dispatchToProps = {
selectView,
};
export default connect(
mapStateToProps,
dispatchToProps
)(CompleteProfileModal);
I am quite perplexed that typescript is even allowing this. Is there a linting rule to disallow the declaration within the component itself?
Upvotes: 0
Views: 414
Reputation: 187124
"I am quite perplexed that typescript is even allowing this."
Typescript will raise errors about things that are wrong, meaning (primarily) things that could cause runtime errors. But shadowing variables is not a problem for running the code. It just means that a variable in a parent scope is no longer accessible because a variable in a tighter scope has the same name. If the code with the shadowed variable doesn't need the variable being shadowed, then the code will run compile fine, and run fine. Typescript will correctly infer the type of the variable that is overriding the one in the parent scope. The code works perfectly fine.
This is the reason typescript doesn't complain. Shadowing doesn't break any rules of the type system, or the language specification.
However, this usually is a bad idea since it can be confusing to the programmer (but not confusing to the Typescript compiler) which variable is actually being referenced. Typescript wouldn't tell you if perfectly functional code is of poor quality. For that, you can use linting.
ESLint (TSLint is deprecated) has a no-shadow rule, which does exactly what you're after.
Upvotes: 1