Vue3中如何从modelValue推断slotProps的类型?
解决Vue组件Slot中Item类型无法推断的问题
要让slot中的item类型自动推断并获得智能提示,核心是让MyComp组件支持泛型,让组件能根据父组件传入的数组类型,自动推导slot参数的类型。
修改MyComp.vue组件
将组件改为泛型组件,通过<script setup>的generic声明泛型参数,同时用泛型约束modelValue和emit的类型:
// MyComp.vue <script setup lang="ts" generic="T"> import { defineProps, defineEmits } from 'vue'; // 用泛型定义props,modelValue为T类型的数组 const props = defineProps<{ modelValue: T[]; }>(); // 对应emit的参数类型也用泛型T const emit = defineEmits<{ 'update:modelValue': [value: T[]]; }>(); </script> <template> <div v-for="(item, index) in modelValue" :key="index"> <slot :item="item" :index="index"></slot> </div> </template>
父组件无需额外修改
父组件中myArray的类型会自动传递给MyComp的泛型参数T,此时slot中的item会被推断为{ name: string; id: number; },即可获得完整的TypeScript智能提示:
// Parent.vue <script setup lang="ts"> import { ref } from 'vue' import { MyComp } from '.'; const myArray = ref([ { name: 'A', id: 1, }, { name: 'B', id: 2, }, ]); </script> <template> <div> <MyComp v-model="myArray"> <template #default="{ item }"> <!-- 现在item类型已正确推断,支持智能提示 --> <div>{{ item.name }} - {{ item.id }}</div> </template> </MyComp > </div> </template>
为什么原代码无法推断类型?
原代码中modelValue被定义为unknown[],TypeScript无法从unknown中推导具体类型。通过泛型组件,我们让MyComp可以接收任意类型的数组,并将该类型传递给slot的item参数,实现类型的自动推断。
内容的提问来源于stack exchange,提问作者Brage
相关产品推荐
相关产品推荐

