Search code examples
typescriptvue.jsvue-composition-apitypecheckingvue-props

What is the best practice to pass null to a required props in component in vuejs?


Stack: vuejs (3.2) + composition API + Typescript + 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({
  show: { type: Boolean, required: true },
  geographicCoordinate: {
    type: Object as PropType<GeographicCoordinate | null>, 
    required: true }
});

page.vue:

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

The variable clickedGeographicCoordinate is initiated to be null at first. And clickedGeographicCoordinate is generated by user click.

The variable show is used to control the visibility of component1. When show is set to true, clickedGeographicCoordinate is guranteed to be not null. Now the problem here is that, vue raise warning in browser say that

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

How to handle this situation?


Solution

  • If you are using composition API with Typescript, you should be able to define your props this way:

    import { GeographicCoordinate } from '@/interfaces/type';
    
    const props = defineProps<{
      show: boolean;
      geographicCoordinate: null | GeographicCoordinate;
    }>();
    

    Using Typescript definition you can more easily define your prop types and use null as a prop type. If you happen to use null as a prop type in options API, it will only disable prop type checking at runtime.

    Also, you can conditionally display your component depending of whether your geographicCoordinate are defined or not, and this way you don't need to assert and check that both types could be used within your component