问题
Learning Vue Composition API (and TypeScript), from the docs I found, I should be using ref(null)
to use by a sub component I have inside <template>...</template>
.
This subcomponent have methods like open()
, and I'm accessing it like this:
setup() {
const subcomponentRef= ref(null);
subcomponentRef.value.open();
return { subcomponentRef };
}
This I agree may show the error Object is possibly 'null'.
pointed to subcomponentRef.value
, but the weird thing is even if I added a condition if (subcomponentRef !== null && subcomponentRef.value !== null) { ... }
, it still shows that error. Why??
Also tried accessing it like subcomponentRef?.value?.open()
but I receive this error Property 'open' does not exist on type 'never'.
.
Also tried adding a Non-null assertions, like confirmation.value!.open();
and receives same error Property 'open' does not exist on type 'never'.
.
Any idea what's wrong here? or maybe instead of using ref(null)
, I should predefine it with the actual component? but I don't have idea how to do that correctly, can't find in docs.
回答1:
Great question! I had the same issue as you and stumbled upon this answer. What worked for me was defining the shape of the object (a typescript interface), so TS knows what is there and what isn't.
Applying this knowledge to your example:
setup() {
const subcomponentRef = ref(null)
subcomponentRef.value.open() // TS error here
}
Becomes:
setup() {
const subcomponentRef = ref<null | { open: () => null }>(null)
subcomponentRef.value?.open()
}
The TS error is now gone because:
- Typescript knows the function
open
is available onsubcomponentRef
because we declared it upfront - With optional chaining we tell Typescript not to look further when
subcomponentRef.value
isnull
orundefined
.
Usually these interfaces are already provided somewhere and don't need to be created manually. So in my case I just had to use the QInput
interface from quasar
to avoid the TS error of resetValidation
not being available:
import { QInput } from 'quasar'
const driverIdInput = ref<QInput>()
driverIdInput.value?.resetValidation()
I hope this helps to clear things up and avoid these nasty errors.
回答2:
You should use the component type using typeof yourComponent
or null
then use ?
to access methods/properties:
setup() {
const subcomponentRef= ref < typeof subcomponent| null > (null);
subcomponentRef.value?.open();
return { subcomponentRef };
}
来源:https://stackoverflow.com/questions/65026253/object-is-possibly-null-on-a-refnull