What is the recommended Typescript definition for creating a route link with Vue Router?

Struggling to determine the appropriate TS interface for route links in Vue 3 + Typescript application.

I have a shared component that displays toast messages, which can contain internal and external links.

The HTML structure is as follows:

// Displaying toast messages using v-for loop
{{ toast.message }}

<button
  class="my-button-class"
  tag="a"
  :to="toast.external_url">
{{ toast.call_to_action }}
</button>

Here is the current Typescript definition for these toast messages, allowing for the use of internal_url or external_url:

import type { RouteRecord } from 'vue-router';


export interface Toast {
  message: string;
  call_to_action: string;
  external_url?: string;
  interal_url?: RouteRecord; // The issue lies here
}

The challenge lies in defining the correct TS interface for internal_url.

Neither RouteRecord nor RouteLocation from the Vue Router docs seem to be fitting. An example usage scenario would be:


addToast({
  message: 'Someone viewed your profile',
  call_to_action: 'Review',
  internal_url: { name: routeNames.profile, query: { id: current_user.id }} 
}  

I initially thought RouteLocation was the right choice, but it also leads to errors.

An error sample when using RouteLocation:

Type internal_url is missing the following properties from type 'RouteLocation': matched, fullPath, hash, redirectedFrom, and 3 more.

Answer №1

If you're looking to navigate to a specific route by using its name and possibly passing query parameters, it's recommended to utilize the RouteLocationRaw interface as indicated in the comment. Nevertheless, when using Vue Router with TypeScript, type inference may sometimes pose challenges.

Make sure to update your Toast interface to accurately define the internal_url property:

export interface Toast {
  message: string;
  call_to_action: string;
  external_url?: string;
  internal_url?: RouteLocationRaw;
}

You can now employ the internal_url property with the RouteLocationRaw type within your code:

import { RouteLocationRaw } from 'vue-router';

// Define your route names
const routeNames = {
  profile: 'profile', // modify this with the actual route name
};

// Sample usage
addToast({
  message: 'Someone viewed your profile',
  call_to_action: 'Review',
  internal_url: { name: routeNames.profile, query: { id: current_user.id }} 
});

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

Using the `import.meta` meta-property is restricted to the `es2020`, `esnext`, or `system` options in snowpack+testing-library and will result in an error

I've been encountering issues while setting up Jest and React Testing Library for the snowpack project. The error message I'm receiving is "The 'import.meta' meta-property is only allowed when the '--module' option is 'es ...

Steps to link two mat-autocomplete components based on the input change of one another

After reviewing the content on the official document at https://material.angular.io/components/autocomplete/examples I have implemented Autocomplete in my code based on the example provided. However, I need additional functionality beyond simple integrati ...

What is the best way to exempt a unique situation from a directive's operation?

While troubleshooting a bug related to search functionality on my page, I encountered an issue with the search component. The search feature is working correctly and returning the expected values. However, when I clear the search criteria, I noticed that t ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

The error message "Invalid export value for Next.js with TypeScript: 'getStaticProps'" indicates a problem with the entry export value

I'm currently diving into the world of Next.js and Typescript, and I've run into an error that has left me stumped as there doesn't seem to be much information available on it: "getStaticProps" is not a valid Next.js entry export value.ts( ...

Preventing duplicate namespace declarations in TypeScript

Let's say I have a variety of objects with the following data structure: { namespace: 'first'|'second'|'third' } Now, I need to include another object with the same data structure, but its namespace cannot be assigned ...

Error: DataTable cannot set the property '_DT_CellIndex' because it is undefined

I am currently utilizing Datatable in my Laravel/Vuejs project. The data is being loaded into the table without any issues, but I am encountering a problem where the search box is not displayed, and I am receiving the following error: Uncaught TypeError ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

Delete an element from an array once an AJAX response has been received

As a Vue.js beginner transitioning from jQuery, I find myself frustrated and struggling with basic concepts for a simple project. Specifically, I am attempting to delete an article only after receiving an ajax response, displaying a spinner while waiting. ...

What is the best way to connect a nested Vuex object to a Vue.js property within the Tiptap text editor?

I'm attempting to connect the nested Vuex state object to the editor property of the tiptap's editor-content component. The structure of the state is as follows: <template> <table :style="{ backgroundColor: element.options.ba ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

What is the best way to create a calendar that displays every day in a single row?

Is it possible to create a calendar with all days in one row? I've been searching for a solution to this problem without any luck. It's surprising that I haven't found a clear answer or explanation on how to achieve this. I'm sure man ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...

Could someone help me understand this JavaScript code where a function takes an object as a formal parameter?

Within a Vue component's methods, I came across the following code snippet defining a function: methods: { onEditorChange({ editor, html, text }) { console.log('editor change!', editor, html, text) this.content = html ...

Can you explain the meaning of the code snippet: ` <TFunction extends Function>(target: TFunction) => TFunction | void`?

As I delve into the contents of the lib.d.ts file, one particular section caught my attention: declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; The syntax in this snippet is a bit perplexing to m ...

Angular 2 destroy outlet-content and refresh the view

Is there a method in Angular 2 to remove a component that was automatically created within a router-outlet? I am looking to destroy it so that a new one is generated when I navigate back to that outlet (or is there a way to reload the outlet?). ...

Issue with importing RxJS in an Angular 5 project

Help needed! I can't find Observable, how do I use rxjs on http? Can someone please provide guidance? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { IEmployee } from '. ...

Experiencing a Typescript issue while trying to set a string as the state of a React component with a specified TS type

I've defined a state in my React component for a specific data type called Color. \\ state const [messageSeverity, setMessageSeverity] = useState<Color>('success'); \\ TS type export type Color = 'success&ap ...

Harnessing the power of VUE.js: Exploring the versatility of V-bind with Array and

I've encountered an issue with an app I'm currently working on. In my project, I am utilizing Vue.js to create the front-end and attempting to apply two classes to a div within a v-for loop. The first class is bound with a filter that functions ...

Discover the use of dot notation for accessing nested properties

In the deps array below, I aim to enforce type safety. Only strings allowed should be in dot notation of ${moduleX}.${moduleX service} // Modules each have a factory function that can return a services object (async) createModules({ data: { factory: ...