I'm trying to use a child component to separate the display of some stuff (the async result of a db query).
I tried provide/inject system from Vue to pass variables between the components.
It works but still the child component seems to complain.
This is a subset of the code to give an idea.
In my parent component:
<template>
<InteractionResults /> <!-- the child -->
</template>
<script setup lang="ts">
import { ref, provide } from 'vue';
const loading = ref<boolean>(false);
const error = ref<boolean>(false);
let interactions = ref<Interaction[]>([]);
provide('search', { error, loading, interactions })
</script>
In my child component (InteractionResults):
<template>
<h6>interactionResults</h6>
{{loading}}
<template>
<script setup lang="ts">
import { inject } from 'vue';
import type { Interaction } from '@/models/Interaction';
const { error, loading, interactions } = inject('search');
// It complains and the 3 variables are highlighted in red.
</script>
The code is working but VS Code complains as follows (interactions for example, but the two other variables give the same error with their respective names):
Property 'interactions' does not exist on type '{ error: any; loading: any; interactions: any; } | undefined'.ts(2339)
injectcannot guarantee that that the value for a key was everprovide-ed, so the return type includes a union withundefined.undefinedobviously has no properties, resulting in the error given by TypeScript.inject().provide/inject, is this the best method for this case? Based on the code you've given, I would say that a prop (or props) on the child component would be better.{ error: undefined, loading: false, interactions: [] }. See also the docs on typingprovide/injectfor how to use them properly and safely with TypeScript.