typescriptvue.js

How to type a wrappers props without preventing it from appearing in attrs?


Wrapper component

<script setup lang="ts">
import InputBase,{ Props as InputBaseProps } from "./InputBase.vue";


interface Props extends InputBaseProps {
  label?: string;
  labelClassName?: string;
...other props
}
const props = defineProps<Props>();
</script>

<template>
  // Wrapper specific stuff that uses the above props
<InputBase v-bind="$attrs"  />
</template>

Wrapped component

<script setup lang="ts">
import InputBase,{ Props as InputBaseProps } from "./InputBase.vue";


export interface Props {
  name:string;
...other props
}
const props = defineProps<Props>();
</script>

<template>
  // InputBase logic

</template>

I want to extract just Wrapper Props out and use it in the wrapper and pass everything down to the base component. How could I go about implementing this so that I get all the prop types in the wrapper but I can still easily extract out the InputBaseProps and give it to the base.

I could do this by removing the extends but then the wrapper looses ts intellisense of the base components props. I've tried destructuring with toRefs but that cause issues.


Solution

  • It's not practical to keep using attrs at this point, they are a simple way to pass the whole set, including event listeners. If this is not the case, props can be transformed in the required way with reactivity API.

    If label and labelClassName need to be used in wrapper component, and the rest need to be passed as is to wrapped component, the respected props objects need to be computed from props, which is readonly reactive object. Destructuring or any type-aware pick and omit helper implementations can be used for this:

    const wrapperProps = computed(() => {
      const { label, labelClassName } = props;
      return { label, labelClassName };
    });
    
    
    const wrappedProps = computed(() => {
      const { label: _label, labelClassName: _labelClassName, ...rest } = props;
      return rest;
    });
    

    Since props is correctly typed, the types of computed props are supposed to be inferred.