The TypeScript compiler is unable to locate the injected property within a Vue Object Component

Struggling with a work example involving injecting a service during Vue's bootstrapping process.

Everything "works" fine in my JavaScript and Class-Component TypeScript versions. However, when using the Vue object API with TypeScript, the compiler throws an error saying that this.sampleService does not exist in my component.

Am I overlooking something?

<template>
  <div class="app">
    {{message}} <fake-button :text="buttonText" @some-click-event="handleClickEvent"></fake-button>
  </div>
</template>

<style lang="scss">
  .app {
    $background-color: #9f9;
    $foreground-color: #000;
    background: $background-color;
    color: $foreground-color;
  }
</style>

<script lang="ts">
  import Vue from 'vue'

  const App = Vue.extend({
    components: {
      FakeButton: () => import('@client/components/fake-button/fake-button-object-typescript.vue')
    },
    data: function () {
      return {
        message: 'Hello World - App Object TypeScript',
        buttonText: 'Click Me'
      };
    },
    inject: {
      sampleService: 'sampleService'
    },
    methods: {
      handleClickEvent(someVal?: string) {
        console.log('App', 'handleClickEvent', someVal);
      }
    },
    beforeCreate() {
      console.log('App', 'beforeCreate');
    },
    created() {
      console.log('App', 'created');
    },
    mounted() {
      console.log('App', 'mounted');
      // TODO: While this compiles, TypeScript complains that it doesn't exist
      console.log('this.sampleService.getDate()', this.sampleService.getDate());
    }
  });

  export default App;
</script>

ERROR in vue-test/src/client/containers/app/app-object-typescript.vue.ts
    [tsl] ERROR in vue-test/src/client/containers/app/app-object-typescript.vue.ts(35,56)
          TS2339: Property 'sampleService' does not exist on type 'CombinedVueInstance<Vue, { message: string; buttonText: string; }, { handleClickEvent(someVal?: s...'.

Answer №1

To tackle this issue, I devised a strategy involving the creation of an interface for the injection process. In a hypothetical scenario, this approach would look something like the following:

<script lang="ts">
import { CustomServiceInjection } from '...';

const App = ( Vue as VueConstructor<Vue & CustomServiceInjection> ).extend({
  inject: {
    customService: 'customService'
  } as Record<keyof CustomServiceInjection, string>,
  // etc.
});
</script>

Furthermore, you can implement this very interface in the component that offers the service:

export interface CustomServiceInjection {
  customService: CustomService; // or any other type associated with your service
}

export default Vue.extend({
  provide(): CustomServiceInjection {
    return {
      customService: new CustomService(),
    };
  },
  // etc.
});

Answer №2

Consider including the provide method in your code. See the example below. It is recommended to utilize vue-property-decorator when working with typescript.

inject: {
      sampleService: 'sampleService'
    },
provide () {
    return {
      sampleService: this.sampleService,
    }
  }

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

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

Transmitting PHP object through AJAX

Can anyone suggest the most effective method for passing a PHP object via AJAX? For instance: //objectClass = objectClass.php $obj = new objectClass(); <a href="javascript:getOutput("some variable", $obj); Since the other file, output.php (called thr ...

What steps should I take to ensure that TypeScript acknowledges the validity of my object assignment?

Trying to implement this code: type A = { b: false, } | { b: true, p: string; } function createA(b: boolean, p: string | undefined): A { if (b && p === undefined) { throw 'Error'; } const a: A = { b, ...

The Laravel and Vue fetch operation is yielding no results on the front end, despite the data being successfully

Within my Vue template, I am using the following code snippet... <template> <div id="container"> {{show_municipality_in_words(12)}} </div> </template> In my JavaScript file... export default { data() { }, met ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

Setting up the CSS loader in a Vue.js project using webpack

I am currently working on a new vue-cli project and have successfully installed the Pure.CSS framework using npm install purecss --save. However, I am struggling to seamlessly integrate, import, or load the css framework into my project. I am unsure of whe ...

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Vue: The function "priceFilter" is not defined in this context

function sanitizeInput(event) { event.target.value = event.target.value.replace(/[^\d.]/g, ""); event.target.value = event.target.value.replace(/^\./g, ""); event.target.value = event.target.value.replace(/\.{2,}/g, "."); event.targe ...

Angular2 Interactive Modal Pop Up

Here is an example of a modal in HTML code: <app-modal #modal1> <div class="app-modal-header"> header </div> <div class="app-modal-body"> You c ...

vue.js does not recognize the property or method

I'm currently in the process of developing a web application using Django and incorporating Vue.js within a template file. However, I encountered an error when attempting to display icons based on predefined data. vue.js:634 [Vue warn]: Property ...

VS Code fails to identify Typescript internal modules

I am currently facing issues with separating my TypeScript classes into distinct files using internal modules. Unfortunately, the main.ts file is not loading or recognizing the sub-modules. main.ts /// <reference path="Car.ts" /> module Vehicles { ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Discovering the correct way of utilizing Vuelidate's minValue and maxValue functionality

I am having trouble figuring out how to validate for values greater than 0. When using minValue(0), it also accepts the value 0. On the other hand, if I use minValue(1), it does not accept any decimal between 0 and 1. Furthermore, I am facing an issue wit ...

Arranging in ascending and descending sequence in Angular2

Is there a way to implement sorting in both ascending and descending order? I currently have code that only allows for sorting in ascending order by name and identifier. How can I modify it to also support sorting in descending order? sortType(sort: strin ...

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...

The event bus for the custom Modal in Vuejs is failing to trigger

I have developed a unique Modal plugin in Vue.js specifically for my Laravel 8 application. The main issue I am encountering revolves around the modal not opening as expected. The plugin itself is implemented within my app.js file: const Modal = { ins ...

TypeScript: defining a custom type with a collection of properties following a consistent pattern

I am looking for a way to create a type that can accommodate any number of properties following a predefined pattern, like so: type Values = { id: number; id1?: number; id2?: number; id3?: number; // ... somethingElse: string; anotherOne: num ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...