Vue: PropType doesn't take undefined for optional props into account

Created on 12 Jun 2020  路  7Comments  路  Source: vuejs/vue

Version

2.6.11

Steps to reproduce

Create component with optional prop being an object and try to access its property

import Vue, { PropType } from 'vue';

Vue.extend({
  props: {
    container: Object as PropType<{ n: number }>,
    // or container: Number
  },

  mounted () {
    // should fail because this.container could be undefined
    console.log(this.container.n);
  },
});

What is expected?

TS error: Object is possibly undefined

What is actually happening?

No error

Note

It works as expected with Composition API plugin

image

improvement typescript

Most helpful comment

Yeah, I guess I didn't emphasised actual problem clear enough, sorry and thanks

All 7 comments

@posva you mean vue behaviour is correct and VCA behaviour is not?

Hi @jacekkarczmarczyk, what's the Object as PropTypeVCA<{ foo: number }> are for?

Do you mean:

defineComponent({
  props: {
    foo: {
      type: Number
    }
  },
  setup (props) {
    console.log(props.foo) // number | undefined  in both VCA and vue-next
  },
})

I originally created this issue in vue repo (not vue-next), I'm not sure why @posva moved it here
In plain vue your example shows number, but IMHO it should be number | undefined, just like in VCA and vue-next

image

Sorry, because you focused on the composition-api error, it confused me

Yeah, I guess I didn't emphasised actual problem clear enough, sorry and thanks

BWT - since type: Number reproduces the problem as well I think PropType in the issue title is not necessary, not sure how what title would be more appropriate though

I edited the code sample to reproduce to not include the Composition API plugin

Was this page helpful?
0 / 5 - 0 ratings