Vue 3 Typescript warning on Vue $emit and $event "Object is possibly 'null'"

Viewed 3218

How to get rid of the TS warning in Vue template?

enter image description here

I'm using the example provided in Vue 3 manual

<input 
   type="text"
   :value="title"
   @input="$emit('update:title', $event.target.value)"
>

Note: This only an TS warning, this works as it should.

3 Answers

My solution with help of Mic Fung. Create an handler method...

But we need some typing...

import { defineEmits } from 'vue'
const emit = defineEmits(['update:value'])

const updateValue = (e: Event) => {
  emit('update:title', (e.target as HTMLInputElement).value)
};
<input
  :value="value"
  type="text"
  @input="updateValue"
/>

My option on the root of the problem: https://github.com/vuejs/jsx-next/issues/234

Try to use optional chaining to handle null situation

$event?.target?.value 
// the two `?` do the following
// if $event is null, the output will be null
// if $event.target is null, the output will be null

// if $event.target.value is null, the output will be null
// only if $event.target.value has value, the output will contain value

UPDATED

If you confirm the event has target and target has value you can use ! to tell typescript there must be target and value in $event

$event!.target!.value 

I was trying to figure out how to do this with JSDoc (standard JS Typescript for VS Code) and within the inline property of @change on the component. (so without the need of an extra function), this is what eventually worked:

@change="event => (modelValue = /**@type {HTMLInputElement} */ (event.target).value)"

This way, you cast the event.target to an HTMLInputElement, which has a value property.

Related