React-Redux项目中如何为Slider组件Props替换any类型?
any with Proper Type for React-Redux Slider Component Props Great question! Let's fix that any type to make your TypeScript code type-safe and aligned with best practices. Here's how to do it step by step:
1. Understand the Props Your Component Receives
Your Slider component gets two props from the connect HOC:
products: Coming from the component's own props (typed asProductType)number: Mapped directly from your ReduxStateType
We need a type that combines these two sets of properties to match exactly what connect passes to the component.
2. Define the Slider Props Type
You have two clean, idiomatic options here:
Option 1: Use a Cross Type
Combine ProductType with the additional number property directly using a cross type:
type SliderProps = ProductType & { number: number };
Option 2: Extend with an Interface
If you prefer interfaces (ideal for future extensibility), extend the existing ProductType:
interface SliderProps extends ProductType { number: number; }
3. Update the Component to Use the New Type
Replace the any in your component declaration with the new SliderProps type:
import { connect } from "react-redux"; import { ProductType, StateType } from "types"; // Define your props type first type SliderProps = ProductType & { number: number }; const Slider = ({ products, number }: SliderProps) => { return ( <S.Slider> <S.SliderWrapper widthSize={number}> {products} ... </S.SliderWrapper> </S.Slider> ); }; export default connect((state: StateType, { products }: ProductType) => { return { number: state.number, products }; }, null)(Slider);
Why This Works
The connect HOC merges the props returned from mapStateToProps (number) with the component's own props (products from ProductType). Our SliderProps type exactly represents this merged set of properties, so TypeScript can properly validate every prop being passed to your component.
This eliminates the unsafe any type while keeping your code aligned with TypeScript and React-Redux best practices.
内容的提问来源于stack exchange,提问作者user12842959

