Hasan Parasteh
Hasan Parasteh

Reputation: 549

Typing the DOM ref in the vue.js typescript

I'm just wondering why my ref to a simple button won't work in typescript. I created a simple button and a constant and then when component is mounted I check if the ref is null or not. otherwise make the button un-disabled...

Here is the example code:

<template>
 <input v-model="phone" type="text" />
 <button ref="phoneSubmitBtn" type="button" disabled>تایید</button>
</template>

<script lang="ts" setup>
import { Ref, ref, watch, onMounted } from 'vue';

const phoneSubmitBtn: Ref<HTMLButtonElement>|Ref<null> = ref(null);
let phone: Ref<string> | Ref<null> = ref(null);

onMounted(() => {
    if (phoneSubmitBtn.value === null) { 
        return false
    }

    watch(phone, () => {
        if (phone.value !== null && phone.value.length === 11) {
            phoneSubmitBtn.value.disabled = false;
        } else{
            phoneSubmitBtn.value.disabled = true;
        }
    })
})
</script>

Note: Logic works fine and everything works as well but the VSCODE tells me that phoneSubmitBtn.value.disabled: Property 'value' does not exist on type 'never'.ts(2339) inside of the watch section.

Upvotes: 3

Views: 1117

Answers (1)

Estus Flask
Estus Flask

Reputation: 223114

phoneSubmitBtn is incorrectly typed, it's narrowed down to Ref<null> on assignment because it's a constant, so the type of phoneSubmitBtn.value is null.

It should have been:

const phoneSubmitBtn: Ref<HTMLButtonElement | null> = ref(null);

Since ref a generic, variable type can be inferred:

const phoneSubmitBtn = ref<HTMLButtonElement | null>(null);

Upvotes: 3

Related Questions