typescriptvue.jsvue-composition-apitypecheckingvue-props

Why vue.js type check for props failed even I use "Object as PropType<GeographicCoordinate | null>"?


Context: vue.js (^3.2.13) + Typescript + Composition API + visual studio code

file type.ts:

export class GeographicCoordinate {
  latitude: number;
  longitude: number;
  altitude?: number;

  constructor(latitude: number, longitude: number, altitude?: number) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.altitude = altitude;
  }
}

component1.vue:

import { GeographicCoordinate } from '@/interfaces/type';
const props = defineProps({
  geographicCoordinate: {
    type: Object as PropType<GeographicCoordinate | null>, 
    required: true }
});

page.vue:

<template>
  <component1
    :geographic-coordinate="clickedGeographicCoordinate" @save-event="saveEvent">. 
  </component1>
</template>
<script lang="ts" setup>
  import { GeographicCoordinate } from '@/interfaces/type';
  var clickedGeographicCoordinate = ref<GeographicCoordinate | null>(null);
</script>

My visual code didn't hint and error here. But when I open it in my Chrome, in console, there is error:

[Vue warn]: Invalid prop: type check failed for prop "geographicCoordinate". Expected Object, got Null

Why vue runtime hint null is not accepted?

And what is the best practice if a component accept a prop value be an instance of a cless or null?


Solution

  • The actual underlying issue is that you have required: true which is in direct opposition to a null value. null is an intentional absence, which means you might as well have not sent any prop value at all for geographic-coordinate. If the prop can be null, then it must not truly be required. Remove the requirement and the warning should vanish.

    const props = defineProps({
      geographicCoordinate: {
        type: Object as PropType<GeographicCoordinate | null>
      }
    })