TS: nullable property in Vue3 component

Hello.

I’m sorry for the possibly a dumb question and my English.

I’ve stuck a bit with such thing: I have nullable properties in the store (for example selected item from collection going to be null when nothing selected). But when I pass such variable to the Vue component as property I get an error about time incompatibility, something like

“Type ‘A | null’ is not assignable to type ‘A’. Type ‘null’ is not assignable to type ‘A’”

It is obvious that this is caused by type of property in component, but I don’t understand how to make it nullable.

I figure out how to solve this by defining computed property with type ‘A | undefined’ in parent component, but such approach looks ugly and leads to overhead and less readability.

Also is is impossible to declare such variables in store as ‘A | undefined’, because TS omits them during compilation and Vue doesn’t adds them to the reactivity system, so nothing works in such case (maybe I’m doing something wrong).

Maybe somebody already was able to solve same problem in the elegant way or can point me where I’m wrong?

Thnak you

P.S. technology stack is TS + Vue3 (Composition API) + Pinia

Hi @d33t
Maybe your Prop(PropName) accepts only string or undefined due to the required: false, but you try to send it string or null. So to accept null you should change the prop type of Prop(PropName) as follows

defineProps({
  PropName: {
    type: String as PropType<string|null>,
    required: false,
    default: '',
  },
});

Hope this helps!!