Defining data types for vue-router meta section

Within my router.ts, I included some meta properties with a 'getter' that I plan to utilize when the component is loaded.

{
    path: "attachments",
    name: "AdminJobsAttachments",
    meta: {
        navbarName: "Attachments",
        getter: "Jobs/getJob", // <- this
    },
    component: () =>
        import("@/views/common/Attachments.vue"),
},

To access this information when the component loads, I do the following:

<script lang="ts">
import { defineComponent, ref, computed } from "vue";
import { useRoute } from "vue-router";
import { useStore } from "vuex";

export default defineComponent({
    setup() {
        const route = useRoute();
        const store = useStore();
        const getter = computed(() => route.meta.getter);
        const routeParam = ref(route.params.id);
        const model = computed(() =>
            store.getters[getter.value](routeParam.value)
        );

        return {}
    }
})

However, I encounter the following error in Typescript:

Type 'unknown' cannot be used as an index type.

Since I am relatively new to Typescript, it's possible I am missing something here. I'm struggling to find a solution to this issue.

Any assistance would be greatly appreciated.

Answer №1

Documentation

To add typings for the meta field, you can extend the RouteMeta interface as shown below:

// Add this to your typings.d.ts or router.ts file
import 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    // Required for every route
    navbarName: string
    // Optional property that may not exist on every route
    getter?: string
  }
}

It's important to note that since getter is optional, make sure to check its presence before using it in your code...

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

How can I inform the compiler of the location of my imports?

I'm trying to assign the current CPU usage to the CPU variable using this code: import * as os from 'os'; cpu = os.cpus(); Here is my code. However, I encountered this error message: ERROR in ./src/app/Controllers/app.component.ts Module ...

The data type does not match the expected type 'GetVerificationKey' in the context of express-jwt when using auth0

I am in the process of implementing auth0 as described here, using a combination of express-jwt and jwks-rsa. However, I encountered an error like the one below and it's causing issues with finishing tsc properly. Error:(102, 5) TS2322: Type 'S ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

I'm currently working on incorporating a rating system into my Vue.js project, but I am struggling to successfully pass the rating values

After carefully reviewing the documentation, I implemented the code below. While I am successfully retrieving data for enquiryDesc, I am encountering null values for rating. Despite trying various troubleshooting steps, the issue with null values persists. ...

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

Allowing the property of interface/type to not overlap

Is there a way to consolidate multiple interfaces/types in Typescript by merging them? The resulting interface should have all shared properties as mandatory and all unique properties as optional. Here is an example: interface ShopUser { userId: string ...

Using Angular 2 with Typescript to call a JavaScript function

How can I correctly invoke a JavaScript function from a component in Angular 2 (TypeScript)? Below is the code for my component: import { ElementRef, AfterViewInit } from '@angular/core'; export class AppComponent implements AfterViewIni ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

Creating a Typescript type for the react-intl component within a single file

Currently, I'm trying to incorporate the injectIntl component directly in the file instead of using the traditional export default injectIntl(Component). However, I am encountering difficulties when it comes to typing the component. This is a snippet ...

Performing a series of HTTP requests within a single @ngrx/effect

I need some guidance as I am new to @ngrx and feeling a bit lost in understanding how it should be used. Let's assume we have an effect named PlaceOrderEffect In this effect, my goal is to handle each request in a specific order. processOrder$ = cre ...

One way to dynamically set the image source in Vue.js is to use the current route

A file contains images where each picture's name corresponds to a route. I am trying to update the img src attribute based on the current route name, but I am only able to access the image name and not the full path. <template> <!-- footer ...

Asyncronous calls in Angular involve executing tasks without

The issue seems to be related to the timing of updates for the controlSelected and isAssessmentDataLoading variables. The updateQuestions() method is invoked within the ngOnInit() method, which is triggered when the component is initialized. However, the ...

Issue with transition animation not triggering on nested router-view in Vuejs

I am encountering an issue with a parent route that contains a nested child route. Within the parent route, the router-view element where the child component is loaded is enclosed in a transition. I expected this setup to enable a smooth transition effect ...

The proper method for referencing TypeScript compiled files with the outDir option

I am currently working on a simple app that consists of two .ts files. These files are compiled using the following tsconfig.js file: { "compilerOptions": { "target": "ES5", "module": "commonjs", "sourceMap": true, "emitDecoratorMetadata ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

How to resolve TypeScript error TS2322 when a function returns an interface

export interface AWSTags { CreatedBy: string; Environment: EnvironmentMap; Name: string; OwnedBy: string; Platform: string; Product: string; Runbook: string; Service: string; } Another script contains the following function to generate an ...

Is there a simple method to eliminate devDependencies from the ultimate package using esbuild?

My current challenge involves using esbuild to package my lambda functions. However, during the build generation for deployment, I encounter an alert indicating that the package size exceeds the limit, as shown in the image below. File too large In explo ...

retrieve an object with enum keys that are indexed

I am faced with a situation where I have a collection of interdependent elements, each identified by a unique code (enumeration). My goal is to retrieve the list of elements that depend on a specific element, and then be able to reference them using myElem ...

Show the key names of a React object

Check out my demonstration here This React TypeScript application showcases the display of an object The structure of the object is as follows: { "default": { "ProductSize": { "min": 32 }, ...

What is the best way to update object property data variables in JavaScript/TypeScript?

I have reorganized the following code to enhance simplicity and reusability. Essentially, my goal is straightforward: I possess a series of empty arrays that are linked to specific keys (which correspond to a set of unique ID's). To populate data int ...