Subscribe on changes!

如何在 defineComponent 中定义 slot 的泛型?

avatar
Jul 11th 2023

Vue version

3.34

Link to minimal reproduction

https://stackblitz.com/edit/vitejs-vite-gpqdjq?file=src%2Fcomponents%2FTsxGenericSlot.tsx

Steps to reproduce

如何在 tsx 中把泛型传递给 slot 的定义中呢?按照官方教程也只能是在 function component 中定义 泛型。作用域无法到达 slots option 这里所以应该怎么写才能在 defineComponents 中对 slots type 进行泛型

export default defineComponent({
  emits: {
    sendMessage: (value: string) => typeof value === 'string',
  },

  // how to generic this type
  slots: Object as SlotsType<{
    default: { foo: string; bar: number };  // i want : default: { foo: T; bar: number };
    item: { data: number };
  }>,

  setup(props: Props, { expose, emit, slots }) {
    expose({
      dd: 'dd',
    });
    return () => (
      <div>
        <div>{slots.default?.({ foo: '', bar: 1 })}</div>
      </div>
    );
  },
});

What is expected?

slots: Object as SlotsType<{
    default: { foo: string; bar: number };  // i want : default: { foo: T; bar: number };
    item: { data: number };
  }>,

What is actually happening?

无法实现 defineComponent 中对 slots 的泛型支持

System Info

No response

Any additional comments?

No response

avatar
Jul 11th 2023

i know how to write template generic as:

<script setup lang="tsx" generic="T extends string | number, U extends {a:string}">
defineProps<{
  id: T
  list: U[]
}>()

defineSlots<{
  default: (props: { item: U }) => VNode
}>()
</script>
avatar
Jul 11th 2023

所以我想知道 defineComponent 里如何实现 slot 泛型 像 template 里一样

avatar
Jul 12th 2023

defineComponent<T>()