Riza Khan
Riza Khan

Reputation: 3158

Declaring types for vue-router meta

In my router.ts I added some meta properties that have the 'getter' then I'm interested in using when that component loads.

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

When the component loads I retrieve that information like so:

<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, Typescript gives me the following error:

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

I'm quite new to Typescript so this maybe something I am overlooking but I'm not able to figure out how to fix this.

Any help is appreciated.

Upvotes: 2

Views: 2863

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37843

Docs

It is possible to type the meta field by extending the RouteMeta interface:

// typings.d.ts or router.ts
import 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    // must be declared by every route
    navbarName: string
    // is optional - does not have to be on every route
    getter?: string
  }
}

Note that as getter is declared as optional property, you are required to test it's presence before using it...

Upvotes: 3

Related Questions