Object is possibly 'null'. on a ref(null)

大城市里の小女人 提交于 2021-01-05 05:51:48

问题


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 on subcomponentRef because we declared it upfront
  • With optional chaining we tell Typescript not to look further when subcomponentRef.value is null or undefined.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!