Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type 'RouteRecordRaw[]' is not assignable to parameter of type 'ConcatArray'. The types returned by 'slice(...)' are incompatible between these types. Type 'RouteRecordRaw[]' is not assignable to type 'never[]'...."

Below are the contents of my files.

DashboardRouter.ts

import { RouteRecordRaw } from "vue-router";
const DashboardRouter: Array<RouteRecordRaw> = [
{
  path: "/",
  redirect: "/dashboard",
  component: () => import("@/layout/Layout.vue"),
  children: [
    {
      path: "/dashboard",
      name: "dashboard",
      component: () => import("@/views/Dashboard.vue"),
     },
   ]
  },
];
export default DashboardRouter;

GuestRouter.ts

import { RouteRecordRaw } from "vue-router";
const GuestRouter: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/auth/Login.vue")
  },
  {
    path: "/password-reset",
    name: "password-reset",
    component: () => import("@/views/auth/PasswordReset.vue")
  },
  {
   // the 404 route, when none of the above matches
    path: "/404",
    name: "error-404",
    component: () => import("@/views/error/Error404.vue")
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404"
  }
];

export default GuestRouter;

Index.ts(Main Router)

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { Mutations, Actions } from "@/store/enums/StoreEnums";
import DashboardRoute from "./DashboardRouter";
import GuestRoute from "./GuestRouter";

const routes: Array<RouteRecordRaw> = [].concat(GuestRoute, DashboardRoute);

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(() => {
  // reset config to initial state
  store.commit(Mutations.RESET_LAYOUT_CONFIG);

  // Scroll page to top on every route change
  setTimeout(() => {
    window.scrollTo(0, 0);
  }, 100);
});    
export default router;

Answer №1

The issue arises when [] is left untyped.

To resolve this, consider utilizing type assertion on the []:

const routes: Array<RouteRecordRaw> = ([] as Array<RouteRecordRaw>).concat(GuestRoute, DashboardRoute);

// or
const routes = ([] as Array<RouteRecordRaw>).concat(GuestRoute, DashboardRoute);

// or
const routes = ([] as RouteRecordRaw[]).concat(GuestRoute, DashboardRoute);

An alternative approach is to utilize spread syntax for arrays:

const routes: Array<RouteRecordRaw> = [...GuestRoute, ...DashboardRoute];

// or
const routes: RouteRecordRaw[] = [...GuestRoute, ...DashboardRoute];

Answer №2

To resolve the issue, you must separate the RouteRecordRaw and bring it in as a type, which is its intended usage:

import { createWebHistory, createRouter } from "vue-router";
import type { RouteRecordRaw } from "vue-router";

I encountered the same issue recently and managed to solve it just a little while ago.

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

Utilizing the Vuex/Redux store pattern to efficiently share a centralized source of data between parent and child components, allowing for customizable variations of the data as

Understanding the advantages of utilizing a store pattern and establishing a single source of truth for data shared across components in an application is essential. Making API calls in a store action that can be called by components, rather than making se ...

Switch out the image for a placeholder whenever the src is updated

I need to update an image with a dynamic src value <img :src="image.url"> Currently, when the image.url changes, the old image remains in place until the new one loads. This delay can create a strange effect as the text details change before the im ...

Turn off the button and add a CSS class to it when sending a message

I have an Angular 7 component with a form that includes the following TypeScript code: export class MessageComponent implements OnInit { message: FormGroup; constructor(private formBuilder: FormBuilder, private messageService: MessageService) { } ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Encountered an issue while executing Jest test with vuejs-datepicker

Currently, I am diving into the world of Jest while testing my Vue application. Everything was going smoothly until I encountered an issue with one of my components that utilizes vuejs-datepicker. Whenever I run the tests below, I consistently encounter an ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

The statement 'typeof import("...")' fails to meet the requirement of 'IEntry' constraint

When trying to run npm run build for my NextJS 13 app, I encountered the following type error: Type error: Type 'typeof import("E:/myapp/app/login/page")' does not satisfy the constraint 'IEntry'. Types of property 'def ...

"Trouble with Vue.js post request: JSON data received but unable to be assigned to Vue's data

Hey there! I'm currently using vuejs and ajax for sending formData and getting a json response. While the json response is being received, I am facing an issue in assigning it to the vue data object. Any suggestions on why this might be happening? Bel ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

How can I incorporate a new user interface button into Here Maps?

I have set up a default interactive map using Nokia Here Maps v3. The map contains multiple markers grouped together. Now, I am looking to add a button or some other UI element to the map that, when clicked, will call a function to zoom in as tightly as p ...

Ways to modify Angular pipe without specifying data types

I am in the process of extracting an Angular pipe from an application to a library. The current pipe is tied to specific types, but I want to change it to use generic types while maintaining type safety. Original Pipe: import { Pipe, PipeTransform } fr ...

Is there a way to add zeros at the beginning of ZIP codes that have only 3 or 4 digits using LODASH or Typescript?

Looking at the JSON data below, it includes information on USPS cities, states, counties, latitude, longitude, and zip codes. With over 349,000 lines of data, it's very extensive. ... { "zip_code": 988, "latitude": 18.39 ...

Utilize the v-if directive with nested object properties for dynamic conditional rendering

I need to verify if the item object has a property called 'url' set. If it's not present, I would like to display a placeholder image. Here is an example of what I want to achieve: <img v-if="item.relationships.main ...

You are trying to reference the property or method "subscribed" during the render process in Vue.js, but it is not defined on

Within my Vue subscribe-button component, I have included all the necessary parts: props, computed properties, and methods. In the computed section, I have defined the subscribed property. However, I am encountering an error: " [Vue warn]: Property o ...

The name "Identifier" has already been declared before

I am currently working on a social network project to enhance my skills in nodejs and reactjs. While debugging the backend code for /signin using Postman, I encountered an error that prevents me from launching the node server. The error message displayed i ...

Tips on sorting a nested array in a React TypeScript project

Hey there! I currently have a working filter in React that utilizes a List (I am using Mantine.dev as my CSS template): <List> {locations.filter(location => { const locServices: Service[] = []; location.services.forEach(service => { ...

Vue.js Asynchronous while loop (continuously checking backend until task completion)

When working inside a vue action, I am interested in continuously checking the status of my backend by calling another async action until a certain task is completed (there will be a loader on the frontend to show progress). To elaborate, I need to keep m ...