Skip to content

Support MaybeRefOrGetter as the type for passing props #8842

Closed
@pleek91

Description

@pleek91

What problem does this feature solve?

Getters are extremely useful to avoid the overhead of computed properties and to pass data that should be re-evaluated when accessed. So something like () => new Date() vs new Date(). #7997 is great and provides some nice tools for handling getters and normalizing values specifically the MaybeRefOrGetter type and the toValue and toRef utilities.

Props basically have the type MaybeRef because you can bind either a static value or a ref :value="new Date()" vs :value="myDateRef". However you cannot pass a getter. Currently in order to do so you'd have to make the type for your prop Date | (() => Date) and then normalize the value using toRef or toValue inside your component. Then you could pass :value="myDateGetter".

It would be a nice developer experience to allow all props to be MaybeRefOrGetter and automatically normalize the value. So you could bind myDateGetter while the prop type would simply Date.

What does the proposed API look like?

DateLabel.vue

<template>
  <span>{{ value.toLocaleString() }}</span>
</template>

<script lang="ts" setup>
  defineProps<{
    value: Date
  }>()
</script>

When using the DateLabel component all three of these would pass type validation and render the date label.

<template>
  <DateLabel :value="dateConst" />
  <DateLabel :value="dateRef" />
  <DateLabel :value="dateGetter" />
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import DateLabel from './DateLabel.vue'
  
  const dateConst = new Date()
  const dateRef = ref(new Date())
  const dateGetter = () => new Date()
</script>

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions