Home  >  Q&A  >  body text

Vue 3: Input 'number|boolean' is not assignable to type 'number';

I'm using Vue 3 and the Composition API and I'm currently trying to add Typescript to my project.

I have a "global input" component that I can call to create any input I want. The component will then render another input component based on the "inputType" prop. For example, I can use global input like this:

<InputBlock input-type="number" :value="15" :min="0" :max="100" />
<InputBlock input-type="check" :value="true" />

InputBlock looks like this:

<script setup lang="ts">
import InputNumber from "./InputNumber.vue"
import InputCheck from "./InputCheck.vue"

const props = defineProps({
  value: { type: [Boolean, Number], required: true }, // Here the value can be type Boolean|Number
  inputType: { type: String, required: true },
  // ...
})
</script>

<template>
  <InputCheck v-if="intputType === 'check'" :value="value" />
  <InputNumber v-if="intputType === 'number'" :value="value" /> <!-- Here it is supposed to be Number -->
</template>

My InputNumber looks like this:

<script setup lang="ts">
const props = defineProps({
  value: { type: Number, required: true },
  // ...
}}
</script>

As you noticed, the InputBlock component can receive different types of values ​​because the value will be used by different child components. But each child component's value attribute can only accept one type. In my InputBlock I get this error: Type 'number | boolean' is not assignable to type 'number'. Type 'boolean' is not assignable to type 'number'. .

Do you know how I can tell Typescript that the value passed in InputCheck will be a Number instead of a Number|Boolean? Is there a way to "coerce" or "cast" a variable? Or am I doing something wrong here?

P粉156983446P粉156983446318 days ago590

reply all(1)I'll reply

  • P粉274161593

    P粉2741615932023-12-06 11:26:45

    It returns an error because typescript doesn't know that inputType.type and value types are related.

    You can try

    
    

    or this

    sssccc
    
    
    

    reply
    0
  • Cancelreply