How can I use TypeScript to wrap a component in Vue 3?

Looking to customize a PrimeVue component (Calendar) by styling it differently and then re-exporting it.

Here's an example in React:

const WrappedCalendar: React.FC<CalendarProps> = (props)=> 
<div style={{background:'green'}}>
    <Calendar {...props}/>
</div>

Struggling with constant TypeScript errors while attempting this. Even tried extending from PrimeVue's Calendar, which also didn't work out.

Below is a simple attempt that isn't cooperating with TypeScript and exhibiting unexpected behavior:

<script setup lang="ts">
import Calendar, { CalendarProps, CalendarSlots } from 'primevue/calendar';
import { defineProps, h, } from 'vue'

const props = defineProps<CalendarProps>()
const slots = defineSlots<CalendarSlots>() 
const CalendarFC = () => {
  return h(Calendar, props, slots)
}
</script>
<template>
  <div :style="{ background: 'green' }">
      <CalendarFC></CalendarFC>
  </div>
</template>

Is there a simpler way to wrap a component while maintaining the same props / emits / slots as the original one and keeping TypeScript in line?

Answer №1

After testing the code snippet provided, it appears to be functioning correctly. If there are any issues, they could potentially be linked to PrimeVue.

Alternatively, utilizing JSX/TSX might offer a more convenient approach for this particular task. For more detailed information, refer to the official Vue.js documentation.

TestChild.vue

<template>
  <div>
    {{ testProp }}
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { defineSlots, defineProps } from 'vue';
import type { Props, Slots } from './shared.type.ts';

defineProps<Props>();
defineSlots<Slots>();
</script>

shared.type.ts

export interface Props {
  testProp: string;
}
export interface Slots {
  default(): any;
}

TestParent.vue

<template>
  <TestChildWrap />
</template>

<script setup lang="ts">
import { defineSlots, defineProps, h } from 'vue';
import TestChild from './TestChild.vue';
import type { Props, Slots } from './shared.type.ts';

const props = defineProps<Props>();
const slots = defineSlots<Slots>();

const TestChildWrap = () => {
  return h(TestChild, { ...props }, slots);
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Systemjs to transpile TypeScript async functions

When I manually build .ts files using the tsc tool, I notice that wrappers are generated for async/await keywords. However, I am facing an issue setting up transpile on-the-fly using SystemJS. Here is my index.htm configuration: <script src="https:// ...

Error: Unable to access unknown properties (reading 'extend')

Struggling to integrate the Vuetify library into my current Vue 3 project, encountering complications. An error message popped up post-compilation: vuetify.js?ce5b:42021 Uncaught TypeError: Cannot read properties of undefined (reading 'extend') ...

Encountering a TypeScript error while trying to pass the myDecorator function as a decorate prop to React

Encountering a TS error that states: (property) decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined Type '([node, path]: [node: any, path: any]) => { anchor: { path: any; offset: string | number; }; focus: { path: any; offset: ...

Exploring Nuxt's Getters with vuex-class for seamless data retrieval

Currently, I am in the process of developing an application using Nuxt and experimenting with vuex for the first time. Despite following numerous tutorials to set it up, I'm encountering difficulties accessing the store and suspect that the issues may ...

What is the method for dynamically invoking computed props in templates?

Here is a similar situation: <script> export default { computed: { example () { return 'bar' } } } </script> <template> <div> <!-- Unfortunately, attempting to call "this" ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

Typescript-optimized Npm library utilizing the module-alias feature

As I work on creating an npm library with Typescript, I have made use of the paths setting in tsconfig.json and the module-alias tool to streamline my imports, allowing me to use syntax like import * from '@/utils'. However, I have encountered an ...

Omit the readme.md file from Vuepress

Currently, I am attempting to remove the README.md from Vuepress in order to utilize it for Github documentation. Instead, I have set up index.md as my homepage. Is there a method to accomplish this task successfully? I experimented with the following ap ...

Eliminate using a confirmation popup

My attempts to delete an employee with a confirmation dialog are not successful. I have already implemented a splice method in my service code. The delete function was functioning correctly before adding the confirmation feature, but now that I have upgrad ...

Error: The type '{ children: Element[]; className: string; }' cannot be assigned to the type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

My current setup involves using Next.js and TypeScript While working in Visual Studio Code, I encountered an error message stating Type error: Type '{ children: Element[]; className: string; }' is not assignable to type 'DetailedHTMLProps&l ...

Sharing properties between components

While this topic has been discussed extensively, I am still struggling with my specific example. In my setup, I have a react-select component nested within another component, which is then part of the larger App component. SubjectSelect.tsx export default ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...

What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting: let m = [ { name: 'Summary', subListExpanded: false, subList: [ ] }, { name: 'Upload', subListExpanded: false, subList: [ ...

Creating a custom `onSubmit` function with Formik, TypeScript, and hooks can be a powerful way

I'm currently creating form onSubmit functions utilizing the useCallback hooks specifically designed for use with the formik library. A sample structure of my component using formik would be as follows: import { useContactForm } from './useCon ...

Encountering an error with Vue and Django Rest Framework that reads "Cannot read property 'title' of null" while using LimitOffsetPagination

Experimenting with Vue to fetch data from a Django Rest Framework API URL has been successful. Upon accessing the API, I am able to retrieve a list of tutorial titles and display the tutorial IDs in the links as expected: Here is a snippet of my HTML file ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Securing the communication with encrypted API request payloads and responses

It concerns me that all data exchanged between the client and server is in raw json format, as it can easily be manipulated by inexperienced hackers trying to tamper with the values. Although it's not possible to hide a secret salt in javascript, I&a ...

Load Vue: Include jQuery globally for all components

When working with vue-loader single file components, I often need to use jQuery in specific components. To do this, I typically import jQuery like so: import $ from 'jQuery' Is there a way to import jQuery globally, making it available for all ...

How can debugging in Chrome be achieved using Typescript?

How is it possible to debug TypeScript in Google Chrome when the browser only understands JavaScript? I find myself debugging my TypeScript files within my Angular project, which was created using Angular CLI, through the Chrome developer tools. However, ...