SimpleJ
SimpleJ

Reputation: 14768

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

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>

Upvotes: 2

Views: 2439

Answers (1)

tony19
tony19

Reputation: 138326

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>

Upvotes: 4

Related Questions