Vue 3: Input 'number|boolean' is not assignable to type 'number';
P粉156983446
P粉156983446 2023-12-05 18:50:47
0
1
629

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粉156983446
P粉156983446

reply all(1)
P粉274161593

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

You can try


or this

sssccc


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template