【问题标题】:Property 'x' is missing in type '{}' but required in type 'Pick<Interface, "x">'. TS2741类型“{}”中缺少属性“x”,但在类型“Pick<Interface,“x”>”中是必需的。 TS2741
【发布时间】:2020-11-18 15:17:01
【问题描述】:

我正在尝试将一些东西从 redux 存储传递到带有connect 的组件。这是我的代码:

家长:

export const MainPage = (
  {
    count,
    handleIncrementClick,
    selectedOfferId,
  }: MainPageProps,
): React.ReactElement => {
  const handleClick = (): Function => handleIncrementClick(count + 1);
  return (
    <div>
      <h1 data-testid="FirstH1">{`Selected offer: ${selectedOfferId}`}</h1>
      <button onClick={handleClick} type="button">
        {`Klikłeś  ${count}  razy`}
      </button>
      <OffersContainer /> {/* It throws the error here */}
    </div>
  );
};

孩子:

  • 容器:

     const mapStateToProps = (state: globalStateType) => ({
       dataset: state.offersDataSet,
     });
    
     const mapDispatchToProps = (dispatch: Dispatch): FSetSelectedOfferIdInterface => ({
       FSetSelectedOfferId: (
         selectedOfferId: selectedOfferIdType,
       ) => dispatch(setSelectedOfferId(selectedOfferId)),
     });
    
     export const OffersContainer = connect(mapStateToProps, mapDispatchToProps)(OffersComponent);
    
  • 组件:

     export const OffersComponent = ({ offersDataSet }: OffersPropsInterface): ReactElement => (
       <>
         {offersDataSet.map(({
           id, firstName, city, price, image, description,
         }): React.ReactElement => (
           <FlexWrapper key={id.$oid}>
             <OfferContainer
               id={id}
               firstName={firstName}
               city={city}
               price={price}
               image={image}
               description={description}
             />
           </FlexWrapper>
         ))}
       </>
     );
    

OffersProps接口:

export interface OffersPropsInterface {
  offersDataSet: OfferPropsInterface[];
}

OfferProps接口:

export interface OfferPropsInterface {
  id: {'$oid': string};
  firstName: string;
  city: string;
  price: number;
  image: string;
  description: string;
}

这似乎是一个简单的问题,但由于某种原因我得到了这个错误:

类型“{}”中缺少属性“offersDataSet”,但类型“Pick”中是必需的。 TS2741

为什么?我没有渲染组件,而是渲染容器,它只需要 offersDataSet 作为数组,这是通过 redux 提供的。我怎样才能使offersDataSet 是强制性的,但仅适用于redux,而不适用于渲染?还是问题完全不同?

【问题讨论】:

    标签: javascript reactjs typescript types react-redux


    【解决方案1】:

    好吧,我很愚蠢。我将 redux 数据分配给了错误的名称。这里:

    const mapStateToProps = (state: globalStateType) => ({
       dataset /* This should've been offersDataSet.*/: state.offersDataSet,
     //^^^ offersDataSet
    });
    

    现在我知道为什么我需要所有类型的类型...

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2019-10-30
      • 2021-07-26
      • 1970-01-01
      • 2022-11-16
      • 2019-09-19
      • 2016-11-22
      • 1970-01-01
      • 2020-12-25
      相关资源
      最近更新 更多