You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux项目中如何为Slider组件Props替换any类型?

How to Replace 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 as ProductType)
  • number: Mapped directly from your Redux StateType

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:37:42