Nimble Stalker
Nimble Stalker

Reputation: 375

Vue 3 PropType doesn't see the interface

I create parent component Product vue with onMonted hook:

setup () {
    let data = reactive({
      product: {},
      productInfo: {},
      loaded: false,
      shippingDate: ''
    })

    onMounted(async () => {
      const product = await findProduct()
      data.productInfo = productInfo(product)
      data.product = product
      data.loaded = true
    })

    return { data }
  },

And children component ProductAttributes

props: {
    product: {
      type: Object as PropType<Product>,
      required: true
    }
  },
  setup (props) {
    const configurableOptions = ref([])
    const configurableChildren = ref([])

    onMounted(() => {
      configurableChildren.value = props.product.configurable_children
      //@ts-ignore
      configurableOptions.value = props.product.configurable_options.map((option: ConfigurableOptions) => {
        option.values = option.values.sort((a: ConfigurableOptionsValue, b: ConfigurableOptionsValue) => {
          return parseInt(a.value_index) - parseInt(b.value_index)
        })
        return option
      })

      // resetAttrs()
    })

    return {
      configurableChildren,
      configurableOptions
    }
  }

But in this case typescript show me an error Property 'configurable_children' does not exist on type 'unknown'.But if I change setup function props to setup (props: { product: Product }) { and change props toprops: ['product'] typescript stops showing error.

Why is this happening? Why does typescript not extract the type from PropType?

PS I use defineComponent

Upvotes: 1

Views: 2282

Answers (3)

Pablo Ezequiel Leone
Pablo Ezequiel Leone

Reputation: 1387

The solution to this is adding a default value with the type:

...
  props: {
    item: {
      type: Object as PropType<IItemModel>,
      required: true,
      default: () => ({} as IItemModel)
    },
  },
...

Upvotes: 1

dean0071
dean0071

Reputation: 46

@Max Stevens is a savior. I was stuck in Vue 3 with typescript solving Property 'x' does not exist on type 'unknown', so every time I passed property, in child component I did this:

Parent:

<some-component :b-prop="{known object 'B' with CustomInterface goes here}">

Child:

props: {
  bProp: Object as PropType<CustomInterface>,
  required: true
},
data () {
  return {
    b: this.bProp as CustomInterface
  }
},
created () {
  console.warn(b.customProperty) // no more errors of unknown
}

It was absolutely annoying, since each property required this additional "wrapping" in data.

After update to 4.5.5 the problem is gone. Now it's just b: Object as PropType<CustomInterface> without bProp and data wrapper Great! Thanks!

Upvotes: 0

Max Stevens
Max Stevens

Reputation: 166

For anyone else encountering the error Property 'x' does not exist on type 'unknown' in this context, I was able to resolve it by upgrading my typescript version from 4.1.5 to 4.5.5.

Upvotes: 2

Related Questions