我正在將 Vue 3 與 Composition API 一起使用,并且我目前正嘗試在我的專案中添加 Typescript。
我有一個“全域輸入”組件,我呼叫它來創建我想要的任何輸入。然后,該組件將根據“inputType”道具呈現另一個輸入組件。例如,我可以像這樣使用全域輸入:
<InputBlock input-type="number" :value="15" :min="0" :max="100" />
<InputBlock input-type="check" :value="true" />
InputBlock 看起來像這樣:
<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>
我InputNumber看起來像這樣:
<script setup lang="ts">
const props = defineProps({
value: { type: Number, required: true },
// ...
}}
</script>
如您所見,InputBlock組件可以接收不同型別的值,因為該值將由不同的子組件使用。但是每個子組件只能為其valueprops接受一種型別。在我的InputBlock我得到這個錯誤:Type 'number | boolean' is not assignable to type 'number'. Type 'boolean' is not assignable to type 'number'.。
您知道我如何告訴 Typescript 傳入的值InputCheck將是 Number 而不是 Number|Boolean 嗎?有沒有辦法“強制”或“強制”變數?或者在這里做錯了什么?
uj5u.com熱心網友回復:
它回傳一個錯誤,因為打字稿不知道 inputType.type 和值型別是相關的。
你可以試試你的
<template>
<InputCheck v-if="typeof value === 'boolean'" :value="value" />
<InputNumber v-if="typeof value === 'number'" :value="value" /> <!-- Here it is supposed to be Number -->
</template>
或這個
<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
})
const isBoolean = (value: any) => typeof value === "boolean"
const isNumber = (value: any) => typeof value === "number"
</script>
<template>
<InputCheck v-if="isBoolean(value)" :value="value" />
<InputNumber v-else-if="isNumber(value)" :value="value" /> <!-- Here it is supposed to be Number -->
</template>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/371631.html
標籤:打字稿 Vue.js vue-composition-api
