Nuxt ts types for VS code of injected properties

1.1k views Asked by At

I am injecting the properties to the nuxt ts context like this:

~/plugins/services.ts

import Vue from 'vue';
import { errorService } from '~/services/error';
import { Plugin } from '@nuxt/types'
const services: Plugin = (context, inject) => {
  inject('errorService', Vue.observable(errorService))
}

export default services

Then i have types file ~/plugins.d.ts

import Vue from 'vue';
import { ErrorService } from '~/services/error';

declare module 'vue/types/vue' {
  interface Vue {
    $errorService: ErrorService
  }
}

declare module '@nuxt/types' {
  interface NuxtAppOptions {
    $errorService: ErrorService
  }
  interface Context {
    $errorService: ErrorService
  }
}

declare module 'vuex/types/index' {
  // this.$myInjectedFunction inside Vuex stores
  interface Store<S> {
    $errorService: ErrorService
  }
}

This is how i use it in the component

<template lang="pug">
  div test
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component({})
export default class ExampleComponent extends Vue {
  mounted() {
    this.$errorService.setErrorMessages('Failed to create meeting','Error message');
  }
}
</script>

I also have shimed the vue files ~/shims-vue.d.ts

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

Everything is building nicely no problem, VS Code can see the type if i use this.$errorService in mixin that is in the .ts file, but if it is in .vue file then shows error that this.$errorService dosn't exist. Should i do something more to make VS Code see the type in the vue files?

2

There are 2 answers

0
Dawid Kisielewski On

@simonPuente

We endup doing this project-vue.ts

import Vue from 'vue';

export class ProjectVue extends Vue {
  $errorService: ErrorService
}

then in the components

export default MyComponent extends ProjectVue {}

It is a bit annoying to add everything to ProjectVue class as programmers may forgot to add it there etc, but it seemed to work for us.

0
AHMED On

I kinda had the same problem, In my case i was trying to place all my injected plugin types into one file which is vue-shim.d.ts so i put it in the root folder ~/vue-shims.d.ts and i declared all my types there just like that: enter image description here

IN SHORT THE SOLUTION: is to add import '@nuxt/types' based on an Issue from GitHub https://github.com/nuxt-community/composition-api/issues/178#issuecomment-664844915

Adding customer declaration type based on docs : https://typescript.nuxtjs.org/cookbook/plugins/#iii-combined-inject