typescript 类型“number”不能分配给类型{}

agxfikkp  于 2023-02-05  发布在  TypeScript
关注(0)|答案(1)|浏览(727)

完全不熟悉TypeScript。我最近对一个同事的代码做了一个重构,实现了Typescript,从那时起我就一直在掩盖错误,但我似乎不能解决这个问题。任何帮助都是很好的!
在此组件中,我验证用户是否已登录,如果是,则根据用户数量显示数据。如果有2个以上的用户,则将显示一个转盘。主要组件功能将显示在一张卡片中。
我收到以下错误:
类型"number"不能赋给类型"BirthdayPerson [][]"。ts(2322)
是否可以将数字类型分配给BirthdayPerson,或者答案取决于逻辑重构?
键入生日人:

export type BirthdayPerson = {
  id: string;
  displayName: string;
  birthday: string;
  picture?: string;
};

生日组件. tsx文件:

interface IMainProps {
  numberOfUsers: number;
  displayData: BirthdayPerson[][];
}

function MainContent({ numberOfUsers, displayData }: IMainProps) {
  return (
    <div>
      <AuthenticatedTemplate>
        {numberOfUsers > 0 ? (
          <Carousel displayData={displayData} />
        ) : (
          <div>
            <h5 className="font-white text-center">Loading...</h5>
          </div>
        )}
      </AuthenticatedTemplate>
    </div>
  );
}

function BirthdayWidget() {
  const isAuthenticated = useIsAuthenticated();
  const users = useUsers();
  const [slideCount, setSlideCount] = useState(2);

  const displayData: BirthdayPerson[][] = useMemo(    // ERROR LIES HERE
    () => updateBirthdays(users, { slideCount }),
    [users, slideCount]
  );
  const hasMoreThanOneSlide = displayData.length > 1;

  const shouldDisplayAmountSelect =
    hasMoreThanOneSlide || (displayData.length === 1 && displayData[0]?.length > 2);

  return (
    <>
      <div className="wrapper">
        <Card
          text="Birthdays"
          displayDropdown={<Select options={ITEMS_PER_SLIDE_ARRAY} onChange={setSlideCount} />}
          displayArrow={!shouldDisplayAmountSelect}
        >
          <>
            <div style={{ marginLeft: 20 }}>
              {isAuthenticated ? <SignOutButton /> : <SignInButton />}
            </div>
            <MainContent displayData={displayData} numberOfUsers={users.length} />
          </>
        </Card>
      </div>
    </>
  );
}

export default BirthdayWidget;

有什么建议吗?
谢谢你:)
我尝试过将"number"类型添加到BirthdayPerson类型中,但它只会给我带来其他错误

g6ll5ycj

g6ll5ycj1#

您的updateBirthdays函数的返回类型不正确。它实际上没有返回number。由于any的原因,Typescript无法指出此错误。我认为正确的类型是:

export const updateBirthdays = (
  people: BirthdayPerson[],
  { slideCount }: IUpdateData
): BirthdayPerson[][] =>
  getBirthdays(people, 30).reduce(
    (resultArray: BirthdayPerson[][], item: BirthdayPerson, index: number) => {
      const result = [...resultArray];
      const chunkIndex = Math.floor(index / slideCount);
      if (!result[chunkIndex]) {
        result[chunkIndex] = [];
        // start a new chunk
      }
      result[chunkIndex].push(item);
      return result;
    },
    []
  );

相关问题