What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below:

<script lang="ts">

import {defineComponent, computed, toRef} from 'vue'
import _ from 'lodash'
import {DateTime} from 'luxon'

interface CalendarEvent {
  start: string
  end: string
  name: string
  id: string
  important: boolean
}

function emptyCalendarEvent(): CalendarEvent[] {
  return [{
    start: '',
    end: '',
    name: '',
    id: '',
    important: false
  }]
}

export default defineComponent({
  name: 'GoogleCalendar',
  props: {
    when: {type: String, default: ''},
    data: {type: Array, default: () => emptyCalendarEvent()},
  },
  setup(props) {

    let allEvents = toRef(props, 'data')
    let importantEvents = computed(() => (allEvents.value.filter((x: CalendarEvent) => x.important)))

(...)

The detailed error message on the final line is

<html>TS2769: No overload matches this call.<br/>Overload 1 of 2, '(predicate: (value: unknown, index: number, array: unknown[]) =&gt; value is unknown, thisArg?: any): unknown[]', gave the following error.<br/>Argument of type '(x: CalendarEvent) =&gt; boolean' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) =&gt; value is unknown'.<br/>Types of parameters 'x' and 'value' are incompatible.<br/>Type 'unknown' is not assignable to type 'CalendarEvent'.<br/>Overload 2 of 2, '(predicate: (value: unknown, index: number, array: unknown[]) =&gt; unknown, thisArg?: any): unknown[]', gave the following error.<br/>Argument of type '(x: CalendarEvent) =&gt; boolean' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) =&gt; unknown'.<br/>Types of parameters 'x' and 'value' are incompatible.<br/>Type 'unknown' is not assignable to type 'CalendarEvent'.

A more clear explanation can be found in the console:

TS2769: No overload matches this call.
  Overload 1 of 2, '(predicate: (value: unknown, index: number, array: unknown[]) => value is unknown, thisArg?: any): unknown[]', gave the following error.
    Argument of type '(x: CalendarEvent) => boolean' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => value is unknown'.
      Types of parameters 'x' and 'value' are incompatible.
        Type 'unknown' is not assignable to type 'CalendarEvent'.
  Overload 2 of 2, '(predicate: (value: unknown, index: number, array: unknown[]) => unknown, thisArg?: any): unknown[]', gave the following error.
    Argument of type '(x: CalendarEvent) => boolean' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => unknown'.
      Types of parameters 'x' and 'value' are incompatible.
        Type 'unknown' is not assignable to type 'CalendarEvent'.
    61 |     let allEvents = toRef(props, 'data')
    62 |     // let importantEvents = computed(() => filteredEvents.value.filter((x: CalendarEvent) => x.important))
  > 63 |     let importantEvents = computed(() => (allEvents.value.filter((x: CalendarEvent) => x.important)))
       |                                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    64 |
    65 |     function extractTime(what: string) {
    66 |       return DateTime.fromISO(what).toFormat('H:mm')

I could use some help understanding what this error message actually means.

Based on my research, it seems like there might be a mismatch in the number of arguments passed to functions. I suspect that in my scenario, it could be related to Vue3's ref concept (just a guess).

Answer №1

By default, the function toRef(...) returns a type of Ref<unknown[]>, which can be explicitly cast to Ref<CalendarEvent[]>:

import {defineComponent, computed, toRef, Ref} from 'vue'
                                       //🔺 import the type Ref
....
  setup(props) {

    let allEvents  = toRef(props,'data') as Ref<CalendarEvent[]>

   let importantEvents = computed(() => (allEvents.value.filter((x) => x.important)))
                                                              //🔺 the correct type is inferred here 

Answer №2

When it comes to the Array props, automatic inference is not possible, resulting in props.data being resolved as type unknown[].

To specify the type of array explicitly, you can declare the prop with the type property set to Array using a type assertion like PropType<YourArrayType>:

import { PropType } from 'vue'

export default defineComponent({
  props: {
    data: {               👇
      type: Array as PropType<CalendarEvent[]>,
      default: () => emptyCalendarEvent()
    },
  },
}

This approach allows TypeScript to accurately infer the type from toRef(props, 'data').

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

Navigate through the pages by selecting from the drop down menu, but the drop down seems to be missing on the second page

Check out this link. I'm interested in exploring each page linked to an item in the dropdown menu at the top of the website. Recently started using selenium, here's what I've been working on: Start by opening the driver Navigate to the w ...

Display detailed information in InfoWindows when markers on a Vue Google Map are clicked

I'm working on creating a map similar to Airbnb's design. Each location marker displays the rental price, and when clicked, a popup with more details appears. However, I'm facing an issue where clicking any marker only shows the details of ...

Failure to retrieve blob - net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)

My fetch request code in my front end for a node js express web app hosted on MS Azure works well for small zip file blobs. However, it times out and displays the error net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK) when dealing with large blobs. ...

What is the best way to determine the moving average of an Object value within an array?

In my dataset, I have an array called 'scores' that contains 4 objects. export const scores = [ { day: '1', Barcelona: 1, Real: 3, Valencia: 0}, { day: '2', Barcelona: 4, Real: 6, Valencia: 3}, { day: '3', Bar ...

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...

Tips for locating and substituting a string in Javascript

Is there a way to locate a particular word within a string and substitute it using JavaScript? For instance Here is a lengthy sentence I want to locate the word "sentence" and modify it to "phrase", resulting in: Here is a lengthy phrase ...

Pinterest-style Angular-UI-Router modal

I am currently working on an app that features a gallery showcasing similar functionalities to . In Pinterest, clicking on a pin displays the pin page above the existing gallery without any information about the background gallery shown in the URL. Users c ...

Leveraging the power of CSS calc() in combination with TailwindCSS styles and JavaScript

Can you explain why applying styles with TailwindCSS v3 to calculations using JS variables does not work? I'm working on a project using VueJS, and I've noticed that styling works fine when using calc as a string like this: ... <div class=&qu ...

Problem importing npm module with Meteor 1.3

I've been trying to follow the guide for using npm packages in Meteor 1.3, particularly focusing on installing the moment npm module. However, I can't seem to work it out despite its simplicity. Every time I attempt to use the package in the cli ...

VueJS 3 custom Checkbox fails to update UI upon clicking

I'm attempting to implement a customized checkbox using Vue 3 and the composition API based on this example. However, despite confirming through devtools that all my props and bound data are successfully passed from the parent component to the child c ...

Develop a radio button filter utilizing the "Date of Creation" attribute, implemented with either jquery or JavaScript

I am currently utilizing a customized Content Query Web Part to load a series of list items. Each of these items has an XSLT attribute known as the Created Date. Shown below is an example of the markup: <div class="item" createddate="2014-01-22 13:02 ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

What are some best practices for creating a Helper in VueJs?

As part of a project, I have developed a method that generates random hexadecimal colors. This functionality will only be used in a few (3 to 5) parts of the project. To keep my main code clean and organized, I would like to separate this color generation ...

What sets apart a post API call from form submission using the post method?

Is it possible to call the payment gateway from Node.js using a POST API call? I understand that traditionally the payment gateway is called through form submission with the method set as post, which redirects to a new page. However, if I use a POST API ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

Challenge with Deploying VueJs: Chrome is stuck on the previous version and not refreshing the application

Having issues with deploying my VueJs project, a web application built on the Metronic template and utilizes Vuetify components. When publishing, I use Visual Studio Code with npm run build and upload the contents of the dist folder to my server. Encoun ...

forEach was unable to determine the appropriate data types

define function a(param: number): number; define function b(param: string): string; define function c(param: boolean): boolean; type GeneralHooks<H extends (...args: any[]) => any> = [H, Parameters<H>] const obj = { a: [a, [1]] as Gene ...

What is the most effective method for integrating templates using AngularJS and Webpack2?

UPDATE: I haven't come across a method to import templates using an import statement rather than require, but I have realized that I can streamline my configuration. In the webpack config, opt for html-loader over ngtemplate-loader for /\.html$/ ...

The issue encountered is a TypeError stating that it is unable to retrieve properties of an undefined value, specifically in relation to the 'imageUrl

When I include the following line of HTML code: <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td> An error is thrown by the console: ERROR TypeError: Cannot read properties of undefined (reading &a ...