Home > Mobile >  How to type my code? (Property 'item' does not exist on type 'object')
How to type my code? (Property 'item' does not exist on type 'object')

Time:06-09

Hi everyone please help me when trying to find a value in my array of objects, I get an error

Property 'item' does not exist on type 'object'

in line el => el.item

how can i fix this

const heroArray = useAppSelector((state) => state.heroList.items)

 const addHero = (item:string, index:number):void => {
    const elements = {
      id,
      item
    }
    dispatch(addItem(elements))
    const b = heroArray.find(el => el.item === 'geovishap-hatchling')
  } 

types/ redux toolkit slice

interface HeroList {
  items: object[];
  elements: {
    id: string | undefined;
    item: string;
  }
}

const initialState: HeroList = {
  items: [],
  elements: {
    id:'',
    item:'',
  }
}

export const heroListSlice = createSlice({
  name: 'heroList',
  initialState,
  reducers: {
    addItem: (state, action: PayloadAction<Object>) => {
      state.items.push(action.payload)
      localStorage.setItem('items', JSON.stringify(state.items));
    },
  },
})

CodePudding user response:

In your interface where you have 'element': {...} make element: SomeInterface. Create another interface that defines that for the element structure.

{
    id:string,
    item:string
}

CodePudding user response:

Do not use object for objects. object in TS means object-like element

const f: object = [];

In your case you need to define type Hero and use it instead of object

type Hero = {
  id: string,
  item: string
}

interface HeroList {
  items: Hero[];
  elements: {
    id: string | undefined;
    item: string;
  }
}

CodePudding user response:

Change line

const elements = {
  id,
  item
}

by

const elements = {
      id:index,
      item
    }

cause you are refering id by index in the function argument

  • Related