Typescript error with assigning array of objects TS Error (2345)

55 Views Asked by At

I'am using next.js with the T3 stack.

The error in the provided code is related to the type incompatibility when updating the solved state using the setSolved function. TypeScript is raising a type error because the code is trying to update the solved state with an array of { word: string[]; difficulty: number | undefined; title: string | undefined; }, but the solved state is of type ISolved[], which expects all items to have a number for the difficulty property.

interface ISolved {
  word: string[];
  difficulty: number;
  title: string;
}
const [solved, setSolved] = useState<ISolved[]>([]);

The Error occures here:

      setSolved((prevSolved: ISolved[]) => {
        const newSolvedItem = {
          word: selected,
          difficulty: data?.find((item) => item.wordString === selected[0])
            ?.difficulty,
          title: getDifficultyTitle(
            data?.find((item) => item.wordString === selected[0])?.difficulty ??
              0
          ),
        };

        return prevSolved ? [...prevSolved, newSolvedItem] : [newSolvedItem];
      });

Full code for this page is here

I tried something like this before however this is obvious why it would have an error

      setSolved([
        ...solved,
        ...data?.sort((a, b) => a.difficulty - b.difficulty),
      ]);

the data has more attributes than the data as data has a structure of GameWords:

model GameWords {
    id          String @id @default(uuid())
    words       Word[]
    easyTitle   String
    mediumTitle String
    hardTitle   String
    trickyTitle String
}

model Word {
    id          String     @id @default(cuid())
    wordString  String
    difficulty  Int
    GameWords   GameWords? @relation(fields: [gameWordsId], references: [id])
    gameWordsId String?
}

0

There are 0 best solutions below