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

Troubleshooting issue: Vue3 datatable does not refresh following Axios request

Why is my datatable not updating after making an Axios request in Vue3 with the composition API? Even though I set the state.tableData to 'test2' and 'test3', the table still shows 'test1'. What am I missing here? Here is th ...

The Threejs Raycaster detects collisions with objects even when the ray is just grazing the surface

Within my Vue component, I have integrated a threejs scene and I am facing an issue with selecting objects using the mouse. I am currently using the OnPointerDown event and raycaster to locate objects under the mouse pointer. However, it seems like the ray ...

What is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

Is there a way to run the mediapipe face detection codepen.io demo on my laptop?

After successfully running the mediapipe face detection demo from Mediapipe official website, I wanted to replicate it on my laptop. To achieve this, I created an 'index.html' file and meticulously transferred the code from the CodePen demo page ...

Error: The property 'setDirections' of undefined cannot be read in Google Maps

As a novice in using the Google Maps API, I am seeking assistance regarding an error I encountered: An issue arises with my code displaying: Uncaught TypeError: Cannot read property 'setDirections' of undefined This occurs at line 101 in google- ...

Using VueJs to associate boolean values with dropdowns

I am currently working on a form with a dropdown menu containing two options: "True" and "False". My goal is to save the selected value as a boolean in the form. For instance, when the user selects "True", I want the value stored as true in boolean format ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

Parsing temporary storage of database query results

My experience with OOP languages like C# and Java has been good, but I am relatively new to JavaScript/TypeScript. I find callback functions confusing, especially when using them with the BaaS ParseDB. For example, finding all playlists for a certain user ...

Different ways to incorporate a property within fabric items

When I attempt to add the editable attribute to an image object in fabric and then use console.log(canvas.toJSON()), the editable attribute does not show up in the object. This is how my code looks: const image = 'https//www.test.com/test.png' f ...

Creating a full-width tab card with Bootstrap-Vue: A step-by-step guide

I stumbled upon something similar in the documentation for bootstrap-vue: A card with tabs: Now, how can I style the tabs to look like this: This is my current code: <b-card no-body> <b-tabs card> <b-tab title="Tab 1" active& ...

Instance property value driven class property type guard

Is it possible to create a class example that can determine the config type based on the value of animalType instance: enum Animal { BIRD = 'bird', DOG = 'dog', } type Base = { id: number } // Object example type Smth = Base & ...

Using Jest: A guide to utilizing a mocked class instance

When working on my frontend React application, I decided to use the auth0-js library for authentication purposes. This library provides the WebAuth class which I utilize in my code by creating an instance like so: import { WebAuth } from 'auth0-js&ap ...

Switching to Next.js

In my Next JS application, I have a div that dynamically displays the currency and price of a product when a user visits a product page. <div className="flex"> <Image src={EuroCurrency} alt="Euro Sign} /> <h1 className=" ...

Having an issue with Vue Dev Tools where the "Open in Editor" button is not functioning properly. Any suggestions on how to resolve this?

I followed a tutorial to implement a new feature, using the instructions found here: https://github.com/vuejs/vue-devtools/blob/master/docs/open-in-editor.md However, I encountered an error: "C:\Users\User\AppData\Local\Programs& ...

What steps should I take to troubleshoot the ParseError related to the restriction of using 'import' and 'export' exclusively with 'sourceType: module' for importing UpgradeAdapter?

I have been working on upgrading an angular.js app to angular 2, following the guidelines provided at https://angular.io/docs/ts/latest/guide/upgrade.html. The application is already coded in Typescript, and we are using browserify and tsify for compiling ...

Issue with Angular Material: Default selection not being applied in mat-select component

When I have a mat-select with options defined as objects in an array, I am facing an issue where the default selected value is not being set when the page renders. In my TypeScript file, I have: public options2 = [ {"id": 1, "name": "a"}, {"id": 2 ...

The Angular template is throwing an error stating that c_r1.getCatType is not a valid function

Within my Angular project (version 9.1.0), I have a class structured like this: export class Contract { contractName: string; limit: number; public getCatType(): string{ if(this.limit > 0) return 'p'; return &ap ...

What is the best way to access a specific property of an object using v-model in vue.js without binding the entire object?

I was working on an input form using HTML and had utilized v-model="upCountryName". Initially, this array was empty but upon clicking the name value, I wrote a function to fetch data from the Django database using Django Rest Framework. Although I successf ...

Utilizing Vuex in Vue with vue-enterprise-boilerplate: A Step-by-Step Guide

I am attempting to incorporate Vuex into my project using the chrisvfritz/vue-enterprise-boilerplate template. However, I am facing uncertainty regarding how to proceed. Within the <script> section of the "courses.vue" view component, the code appea ...