Tomas Gil Amoedo
Tomas Gil Amoedo

Reputation: 595

Getting "object is possibly null" TypeScript error when using template ref value in Vue

I am referencing an <h1> with ref="header". I'm trying to change CSS rules but a TypeScript error is not letting me.

const header = ref<HTMLElement | null>(null)

onMounted(() => {
  header.value.style.color = "red"
})

screenshot of error message

Upvotes: 0

Views: 1121

Answers (1)

Darryl Noakes
Darryl Noakes

Reputation: 2790

The error is perfectly reasonable: you can't be sure that that element exists. And if the element doesn't exist, the template ref's value will be null. It's actually right there in the type for the ref: HTMLElement | null.

You can change your onMounted callback to the following to check for that:

onMounted(() => {
  if (header.value)
    header.value.style.color = "red"
})

Upvotes: 2

Related Questions