In Vue3, automatically infer a type for a slotProp based on the modelValue

In simplifying the component I aim to create, I have created the following code structure:

// MyComp.vue

<script setup lang="ts">
import { PropType, defineProps, defineEmits } from 'vue';

const props = defineProps({
    modelValue: {
        type: Array as PropType<unknown[]>,
        required: true,
    },
});

const emit = defineEmits({
    updateModelValue: (value: unknown[]) => true,
});
</script>

<template>
    <div v-for="(item, index) in modelValue" :key="index">
        <slot :item="item" :index="index"></slot>
    </div>
</template>
// Parent.vue

<script setup lang="ts">
import { ref } from 'vue'
import { MyComp } from '.';

const myArray = ref([
    {
        name: 'A',
        id: 1,
    },
    {
        name: 'B',
        id: 2,
    },
]);

</script>

<template>
    <div>
        <MyComp v-model="myArray">
            <template #default="{ item }">
                <!-- item is of type unknown - type not inferred :( -->
                <div>{{ item }} </div>
            </template>
        </MyComp >
    </div>
</template>

The issue lies in the fact that the type of item does not get inferred, resulting in a lack of IntelliSense support.

How can this be resolved effectively?

(Additional details were added to comply with StackOverflow requirements)

Answer №1

It appears that you have explicitly set the type of your array item to unknown. At this point, TypeScript may not have anything more to infer.

If you are working with Vue version 3.3 or higher, you can utilize generic components:

// MyComp.vue

<script setup lang="ts" generic="T">
import { PropType } from 'vue';

const props = defineProps({
    modelValue: {
        type: Array as PropType<T[]>,
        required: true,
    },
});

const emit = defineEmits({
    updateModelValue: (value: T[]) => true,
});
</script>

This approach will correctly infer types, as demonstrated in this playground

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

What is the best way to implement a filter for incoming data within a function?

I am attempting to trigger a function when a button is clicked using Vue. I need to apply a specific filter to the data being passed into the function in order for it to execute correctly. Below is my attempt: <button v-on:click="functionName(variable| ...

Tips for using rspec to test front end functionality?

In my Rails project, I have incorporated Vue.js using only the core library. Currently, most forms in the project are developed with Vue.js. When testing front-end features like form filling or validations using feature tests in RSpec, I found it to be qui ...

creating and managing multiple redirect routes in vue.js application

const router = new VueRouter({ routes: [ {path: '*', redirect: '/'} } )} I have configured this as the default redirect route in my routes.js file. Now, I am wondering how I can set multiple redirect paths and trigger them ...

Can discriminated unions solely be utilized with literal types?

When looking at the code snippet below, I encountered an issue with discriminating the union type using the typeof operator. function f(arg: { status: number; one: boolean } | { status: string; two: boolean }) { if (typeof arg.status === "number&q ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

The Chronicles of Vue 3

I have successfully set up Storybook for Vue, but I am facing some issues with how it handles Vue 3 components. I suspect the problem lies in the versions - my Vue version is @vue/cli 4.5.11 (checked with "vue -V") and the Storybook version is 6.1.17 (che ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

Update: When a variable changes during onUploadProgress in Vue.js, the DOM is not re

Having a bit of an issue here. I'm working on an app where users can upload images using axios. In order to enhance the user experience, I'm trying to implement a loading bar. Here's what it looks like: <div class="loadingbox" :style="{ ...

TypeScript purity - "The variable exports is not defined"

I encountered an issue with my simple client-server TypeScript application where every import statement in my client.ts file triggers a ReferenceError: exports is not defined error in the browser after loading the HTML. Here is the project structure: root ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

NextImage's ImageProps is overriding src and alt properties

I've created a wrapper called IllustrationWrapper that I'm utilizing in different components. import Image, { ImageProps } from 'next/image'; const getImageUrl = (illustrationName: string) => { return `https://my-link.com/illustra ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

TypeScript encountered an error with code TS2554, indicating that it was expecting 0 arguments but instead received 1 in an Ionic application

Hello everyone! I'm encountering an issue in my project involving a Type Script error TS2554: Expected 0 arguments, but got 1. This error is preventing me from being able to select other options for custom input pop up. In this forum post, I have shar ...

The type 'number | { percent: number; }' cannot be assigned to the type 'string | number | undefined' according to ts(2322) error message

Presently, I am engaged in a project utilizing React and Typescript, where I am working on implementing a progress bar using react semantic-ui. I have encountered a typescript error in my code. Here is the segment causing the issue: import React, { Compo ...

How can I send 'blocking' parameter to getStaticPaths function in Next.js using TypeScript?

Whenever I try to use fallback: 'blocking', in my Next.js page, TypeScript throws an error. I am using the latest 12.2.0 version of Next.js. What could be causing this issue? Type '() => Promise<{ paths: any; fallback: string; }>&ap ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...

Why is my Vue/MySQL Database not showing up online, even though it is accessible locally?

While my application runs smoothly locally, I encounter an issue when deploying to the Heroku server. The page contents linked to the MySQL Database fail to display without any CORS errors or fetch call issues in Chrome Dev Tools. The page loads, but remai ...

Define the expected argument type of a function as an arrow function

In TypeScript, is there any way to enforce the use of arrow functions as function arguments? For instance, when using a publish-subscriber model and passing a listener function to a 'server' object, the server calls this function whenever a publi ...

Custom fields provided by Express are not accessible within routes

In my customExpress.d.ts file, I have defined an extended type: declare namespace Express { export interface Request { user: { id: string; }; } } I have also configured it in the tsconfig.json file: ... "typeRoots": ["sr ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...