Home > OS >  How do I get an input's `checked` state in Vue 3 with Typescript
How do I get an input's `checked` state in Vue 3 with Typescript

Time:10-01

I'm using Vue 3 and TS 4.4. I'm trying to get a checkbox value without having to do this: (event.target as any).checked. Is this possible in Vue? What's the right way to do this?

<script setup lang="ts">
function doThing(checked: boolean) {
  console.log("Do thing", checked);
}
</script>

<template>
  <input
    type="checkbox"
    @change="(event) => doThing((event.target as any).checked)"
  />
</template>

CodePudding user response:

The type assertion (i.e., using the as keyword) is unavoidable here, but you can replace any with the actual type of the event target (HTMLInputElement in this case) to access the checked property.

<template>
  <input
    type="checkbox"
    @change="(event) => doThing((event.target as HTMLInputElement).checked)"
  />
</template>
  • Related