• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by Mark DS


28 Nov, 2024

Updated at 13 Dec, 2024

Improving Type Safety in `defineSlots`

The current documentation for the defineSlots macro offers the following example:

const slots = defineSlots<{
  default(props: { msg: string }): any
}>()

This example works well for defining slot props, but it raises questions about the return type of the slot function, which is currently typed as any. While this is sufficient for many use cases, could it be improved for scenarios where developers interact with slots programmatically in a component’s script?

For instance, consider the alternative of leveraging the Slot type from the @vue/runtime-core package. This type explicitly represents a slot function and can be used as follows:

import type { Slot } from '@vue/runtime-core'

const slots = defineSlots<{
  default: Slot<{ msg: string }>
}>()

Questions for the Community

  1. Should the Return Type Be More Explicit?

    • Does the use of any in the current example provide enough clarity and type safety, especially when working with slots in a script context?
  2. Future Considerations

    • Are there any future plans or a roadmap to support stricter typing for slot content checking as noted in the documentation?
  3. Documentation Enhancements

    • Should alternative examples like the use of Slot be added to the documentation to cater to developers seeking higher type safety in specific use cases?

Example Use Cases

Here’s a comparison of how the current approach and the Slot-based approach handle programmatic slot interactions:

Using any (Current Documentation)

const slots = defineSlots<{
  default(props: { msg: string }): any
}>()

if (slots.default) {
  slots.default() // => any
}

Using Slot

import type { Slot } from '@vue/runtime-core'

const slots = defineSlots<{
  default: Slot<{ msg: string }>
}>()

if (slots.default) {
  slots.default() // => VNode[]
}

Inviting Feedback

I’d love to hear thoughts from the community:

  • Have you encountered scenarios where the return type of a slot function posed challenges?
  • Do you think introducing stricter typing would improve or complicate the development experience?
  • Should the documentation include both approaches to provide developers with options?