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?
2
Answers
You can handle component1 visibility by v-if, when show is false or geographicCoordinate is null, the component is not display and processing data.
If you are using composition API with Typescript, you should be able to define your props this way:
Using Typescript definition you can more easily define your prop types and use
null
as a prop type. If you happen to usenull
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