Reputation: 14796
I'm building a React Native app with TypeScript and React-Redux.
I connected my component using connect:
import { addTodo } from "../../redux/actions";
export interface Props {
addTodo: (todo: Todo) => void;
}
// ... component code
handleAdd = (todo: Todo) => {
const { addTodo, ... } = this.props; // ... = more destructuring
// some code ... eventually:
addTodo(todo);
}
export default connect(
mapStateToProps,
{ addTodo }
)(MyComponent);
The problem is now, that TSLint complains about a shadowed variable:
[tslint] Shadowed name: 'addTodo'
This feels like a mistake from TypeScript not recognizing React-Redux' functionality. I mean it's taught in the Redux docs to map dispatch to props this way.
Am I doing something wrong? Or do you have to do this differently when using TypeScript?
Upvotes: 5
Views: 4754
Reputation: 222720
This is the result of TSLint no-shadow
rule. It allows to avoid mistakes that result from unintentionally shadowed variables. And it requires to provide workarounds for variables that could be safely shadowed.
Here addTodo
import is shadowed by addTodo
prop. It seems this was intentional, the rule is an obstacle in this case.
Such problems with no-shadow
can be avoided by enforcing a style where objects aren't destructured if variables may become ambiguous. This allows to resolve common problems with similarly named properties, e.g. in props
and state
objects. This also can improve the readability in some places because no backtracking is needed, while other places may become more verbose:
import * as actions from "../../redux/actions";
// ... component code
handleAdd = (todo: Todo) => {
const { props } = this;
// some code ... eventually:
props.addTodo(todo);
}
export default connect(
mapStateToProps,
{ addTodo: actions.addTodo }
)(MyComponent);
For multiple action creators as props, some pick
implementation could be used instead of { addTodo: actions.addTodo }
.
This style may be in conflict with ESLint prefer-destructuring
rule.
Upvotes: 3