Improve-Type-Safety-and-State-Access-in-useStateWithDeps-Hook #3027
+3,709
−3,048
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request aims to improve the type safety and reliability of the useStateWithDeps hook in React. Specifically, the changes address potential issues with accessing state properties using dynamic keys, ensuring that TypeScript correctly identifies and enforces the types of state properties.
Changes Implemented:
Type-Safe Iteration:
Replaced the direct for...in loop with a more type-safe iteration using Object.prototype.hasOwnProperty.call() to avoid errors related to iterating over unexpected properties.
Non-null Assertion:
Added a non-null assertion (payload[k]!) to ensure that payload[k] is not undefined when updating the state, preventing runtime issues.
Improved Type-Safe Access:
Used const k = key as keyof S to inform TypeScript that key is a valid key of S, improving the type inference and ensuring that currentState[k] and payload[k] are correctly typed.
Functional Consistency:
The changes maintain the core functionality of the hook while improving its safety and performance, ensuring that it tracks dependencies and triggers re-renders as intended.
This PR does not alter the primary behavior of the hook but makes the code more robust and type-safe, improving maintainability.