typescript - 对于结合了文本和数字的代码,我应该使用什么输入类型?如何在 TypeScript 中声明以避免错误?

我正在使用 VueJs(来自 React,所以我是新手),并且我有这个输入,其中包含一个代码 => 元音和数字的组合。我有两个问题,首先

我不确定哪个是输入的正确类型,并且在第二种情况下,我的 var 定义为 number |字符串抛出错误。

我知道这可能是一种愚蠢的问题,但我是 Vue & TypeScript 的新手,所以如果你能告诉我正确的方法,那将非常有帮助。

这是代码:

<template>
  <form>
    <label>Code</label>
    <input 
      type="text"
      placeholder="enter a code using only vowels and numbers"
      required
      maxlength="15"
      minlength="7"
      v-model="codeValue"  <!-- Error here -->
      @blur="handleFocus"
      
       />
    <span v-if="focused">You should only enter vowels and numbers.</span>
  </form>
</template>

<script lang="ts">
import {defineComponent} from 'vue'

export default defineComponent({
  name: 'InputValidations',
  data() {
    return {
      emailValue: '' as string, 
      selectedNumber:0 as number,
      codeValue: '' as string | number, 
      focused: false as boolean
    }
  }
})
</script>

错误来自 v-model="codeValue" 并说:

Argument of type 'string | number' is not assignable to parameter of type 'string | null | undefined'.
  Type 'number' is not assignable to type 'string'.VueDX/TS(2345)

回答1

我认为问题在于您使用的是 VueDX,我注意到它根本无法正常工作。

切换到 https://marketplace.visualstudio.com/items?itemName=vue.volar,官方https://vuejs.org/guide/typescript/overview.html#ide-support,特别是对 TypeScript 的支持。同时安装 https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin

相似文章

随机推荐

最新文章