johnsoncodehk / vue-tsc

vue-tsc --noEmit && vite build
https://www.npmjs.com/package/vue-tsc
MIT License
241 stars 6 forks source link

Vue 3 + TS event types error #29

Closed igbominadeveloper closed 3 years ago

igbominadeveloper commented 3 years ago

I created a reusable component with this template

<template>
  <label :for="label" class="mb-1 text-sm flex items-center">
    <input
      type="checkbox"
      :id="label"
      :checked="modelValue"
      class="mr-1 rounded-sm"
      @change="$emit('update:modelValue', $event.targe.checked)"
      v-bind="$attrs"
    />
    {{ label }}
  </label>

  <p>{{ error }}</p>
</template>

When I run vue-tsc, I get these errors:

src/components/BaseCheckbox.vue:8:43 - error TS2531: Object is possibly 'null'.

@change="$emit('update:modelValue', $event.target.checked)"

src/components/BaseCheckbox.vue:8:57 - error TS2339: Property 'checked' does not exist on type 'EventTarget'.

@change="$emit('update:modelValue', $event.target.checked)"
                                                         ~~~~~~~

To be honest, I am not sure this is a vue-tsc problem, I just don't know where to turn to. Any help is welcome

johnsoncodehk commented 3 years ago

When vue support typescript in template(https://github.com/vuejs/vue-next/issues/1359), you can fix it by this ($event.target as any).checked.

But for now you need to use a helper function:

<template>
...
@change="emitModelValue"
...
</template>

<script lang="ts">
...
function emitModelValue(event: Event) {
  emit('update:modelVolar', (event.target as any).checked);
}
...
</script>

You can ask TS question in Vue Discord next time, you will have more immediate response.