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

Something went wrong trying to retrieve the compiled source code of https://deno.land/[email protected]/path/mod.ts. It seems the system is unable to locate the specified path. (os error 3)

Upon executing my main.ts script using deno, I encounter the following error message: error: Failed to retrieve compiled source code from https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcccbdbff8f918a86918f"& ...

An issue was encountered at node_modules/@fullcalendar/core/main.d.ts(1196,54), error TS1144: Expecting either '{' or ';'

When attempting to execute npm run build in my project, I encountered the following error: ERROR in node_modules/@fullcalendar/core/main.d.ts(1196,54): error TS1144: '{' or ';' expected. node_modules/@fullcalendar/core/main.d.ts(1197,34 ...

Using Vue file to access a custom JavaScript object

I have a specialized entity called Plan that is utilized across various files in my project. Currently, I redundantly redefine the entity Plan wherever it's needed. This approach is not efficient, so I decided to consolidate this entity into a single ...

Creating detailed documentation comments for TypeScript within Visual Studio

When using C# with ReSharper and StyleCop, I am able to automatically generate basic documentation comments for methods. This includes sections such as: /// <summary> /// The login. /// </summary> /// <param name="returnUrl" ...

How to simulate a long press mouse click in Vue testing

After developing a custom helper for simulating long click actions with the mouse, such as pressing the left click for one second, I now want to test it using vue-test-utils. However, my search for relevant information on this topic has come up empty-hande ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

What steps should I take to import a module with type definitions? (receiving error TS2656: ...not a module)

I am currently working on enhancing the type definitions for a simple npm module called emitter20. The source code of this module spans 20 lines and looks like this: module.exports = function() { var subscribers = [] return { on: function (eventNa ...

The Vue component fails to display the updated data even after the prop data has been modified

This is the parent component called abc.vue <v-card outlined class="mt-4"> <DetailsTable v-show="toggleClientData" :columnDefs="columnDefs" :rowData="rowData" /> </v-card> methods:{ aggridData() { let self = this; th ...

Encountering issues with bidirectional data binding functionality

I have integrated a pagination component from ng-bootstrap into a generic component that includes a select dropdown to choose the number of items per page. I triggered an event from this generic component and caught it in the parent component (member-list. ...

Is it possible to assign default values to optional properties in JavaScript?

Here is an example to consider: interface Parameters { label: string; quantity?: number; } const defaultSettings = { label: 'Example', quantity: 10, }; function setup({ label, quantity }: Parameters = { ...defaultSettings }) { ...

How to Send Data with NodeJS by Utilizing the Finish Event

Is there a way to retrieve the JSON data sent during the nodejs finish event? This is how I send the JSON data: oResponse.json({ version: "1.0.0", author: "Someone", contributors: "also Someone" }); I would like ...

JavaScript's data.map function cannot be found

I've been developing a full stack application using Vue.Js, NodeJS, ExpressJS, and MongoDB. In my frontend code, I have a PostService.js class that manages HTTP requests to the API. However, I encountered an issue while trying to map the response data ...

Google's geolocation.getCurrentPosition function fails to function properly on mobile devices after the page is refreshed

I recently created a website that utilizes the Google Geolocation JavaScript API along with the vue2-google-maps package. Here is a snippet of the relevant code: `geolocate () { var self = this this.loading = true navig ...

Is there a way to eliminate properties in typescript without relying on the option feature?

I am struggling with removing properties in TypeScript. type Person<GN> = { getName: GN extends never ? never : GN, } const foo = <GN>(person: Person<GN>) => person const first = foo({}) // This should work const second = fo ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Determine data types for functions in individual files when using ElysiaJS

Currently, I am utilizing ElysiaJS to establish an API. The code can be found in the following open-source repository here. In my setup, there are three essential files: auth.routes.ts, auth.handlers.ts, and auth.dto.ts. The routes file contains the path, ...

TypeScript - The key is missing from the type definition, yet it is present in reality

I'm currently working on developing my own XML builder using TypeScript, but I've run into a significant issue: Property 'children' does not exist in type 'XMLNode'. Property 'children' does not exist in type &apos ...

When working with TypeScript, it's important to note that an implicit 'any' type may occur when trying to use an expression of type 'string' to index a specific type

Currently, I'm attempting to transfer a custom hook used in Vue for handling i18n from JavaScript to TypeScript. However, I am encountering a persistent error message: An element is implicitly assigned the type 'any' due to an expression o ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

The circular reference error in Typescript occurs when a class extends a value that is either undefined, not a constructor,

Let me begin by sharing some context: I am currently employed at a company where I have taken over the codebase. To better understand the issue, I decided to replicate it in a new nestjs project, which involves 4 entities (for demonstration purposes only). ...