Home > Net >  Access props object properties Vue 3 TS
Access props object properties Vue 3 TS

Time:02-02

I'm having trouble accessing the properties of my sent object from my parent component. In my child component, I would like to access "found" in the object "lettersState" (see code below). When I try to access "found" in my child component. refer the error message

Property 'found' does not exist on type 'Object'.

parent component :

const state = reactive({
  guesses: ['', '', '', '', '', ''],
  solution: '',
  currentRow: 0,
  lettersState: {
    found: [] as string[],
    miss: [] as string[],
    hint: [] as string[],
  }
})
<template>
  <Keyboard @handleKeyboard="handleKeyboard" :lettersState="state.lettersState" />
</template>

child :

const props = defineProps<{lettersState:Object}>()
console.log(props.lettersState.found)

CodePudding user response:

const props = defineProps<{lettersState:Object}>()

tells typescript that your props look like this:

{
  lettersState: {}
}

But looking at :lettersState="state.lettersState" you want it to be:

type LetterState = {
  found: string[]
  miss: string[]
  hint: string[]
}
const props = defineProps<{letterState: LetterState}>()

CodePudding user response:

You're passing :lettersState="state.lettersState", and then you access console.log(props.lettersState.found). If you look closer, you can see that letterState does not exist in what you passed as a prop: You only passed the value corresponding to letterState. Therefore, there is no need to access the letterState key. Try this:

const props = defineProps<{
    found: string[],
    miss: string[],
    hint: string[]
  }>()
console.log(props.found)
  • Related