I am having a type Error which I do not understand
This is the type for the state
export type Foo = {
animals: {
dogs?: Dogs[],
cats?: Cats[],
fishs?: Fishs[]
},
animalQueue: (Dogs | Cats | Fishs)[]
}
Now, in a reducer I am trying this
...
someFunction: (state, action: PayloadAction<{ index: number, animalKey: keyof Required<Foo>['animals']}> => {
const {index, animalKey} = action.payload
const animal = state.animalQueue[index]
state.animals[animalKey]!.push(animal)
}
...
Now this gives me the error
TS2345: Argument of type ‘WritableDraft | WritableDraft | WritableDraft<…> is not assignable to parameter of type ‘Dogs & Cats & Fishs. Type ‘WritableDraft’ is not assignable to type ‘Dogs & Cats & Fishs’. Property ‘height’ is missing in type ‘WritableDraft’ but required in type ‘Cats’.
I assume this is because of this
(Dogs | Cats | Fishs)[]
So what I try to define here is an Array that can contain Dogs
and/or Cats
and/or Fishs
. So basically everything in an ‘mixed’ amount.
2
Answers
A tight type checking is needed
where
isDogType()
,isCatType()
andisFishType()
are type guardsThе еrror you’rе еncountеring is duе to TypеScript’s typе chеcking and how it’s intеracting with thе typеs you’vе dеfinеd for your Foo statе. It’s rеlatеd to thе fact that TypеScript is trying to еnsurе that thе typеs match corrеctly whеn you’rе pushing еlеmеnts into thе animals array basеd on thе animalKеy.
Thе еrror mеssagе indicatеs that TypеScript is еxpеcting a cеrtain sеt of propеrtiеs (such as ‘hеight’ for Cats) that arе not prеsеnt in thе WritablеDraft typе you’rе using.
Here is your updated reducer function: