What methods can be used to resolve errors stemming from nesting classes within classes in TypeScript?

My experience with TypeScript is limited, and I'm facing an issue. The code appears as follows:

1) Main.ts:

import gpbApi from '@/utils/api/gpbApi';

@Component
export default class ExtendedDetailAccountComponent extends mixins(CurrentUserMixin) {
  ...
  async created() {
    try {
      console.log('gpbApi =', gpbApi);
      const result = await gpbApi.leadService.getReqtypes();
      console.log('result =', result);
    } catch (error) {
      console.log('error = ', error);
    }
  }
  ...

2) vue.d.ts:

import gpbApi from './utils/api/gpbApi';

declare module 'vue/types/vue' {
  interface Vue {
    $gpbApi: typeof gpbApi;
  }
}

3) gpbApi.ts:

import leadService from '@/utils/api/leadService';

class GpbApi {
  leadService!: typeof leadService;
}

const instance = new GpbApi();
export default instance;

4) leadService.ts:

import axios from 'axios';

const path = '...';

class LeadService {
  async getReqtypes() {
    const { data } = await axios.get(`${path}/Reqtype`, { withCredentials: true });
    return data.data;
  }
}

const instance = new LeadService();
export default instance;

I am encountering the following error:

leadService: undefined
error =  TypeError: Cannot read properties of undefined (reading 'getReqtypes')
    at VueComponent.created

What is the solution to resolve this error?

Answer №1

It appears that the leadService field of GpbApi is never instantiated.

Therefore, it is necessary to instantiate the loadService field within the gpbApi

class GpbApi {
  leadService = leadService;
}

Answer №2

My recommendation would be to eliminate the typeof keyword from the declaration of interface properties, as shown below:

interface Vue {
  $gpbApi: gpbApi;
}

Similarly, it is advised to do the same for class definitions:

class GpbApi {
  leadService!: leadService;
}

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

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Using Angular, you can effortlessly inject elements into the editable div from any location on the page

Currently, I am working on developing an HTML interface that allows users to input text and send it as a notification to our mobile application. However, I am encountering challenges with the text and dynamically inserted elements using Angular 5; The te ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

Extracting event handlers using @ContentChildren: A guide

I am dealing with a my-button component that needs to be enclosed within a my-button-row component in the following manner: <my-button-row> <my-button [label]="Some Label" (click)="func1($event)"></my-button> <my-button [label ...

Exploring the process of inferring union types in TypeScript

const type p1 = { a: number, b: string } const type p3 = { a: string } const type p4 = p1 | p3 let sample: p4 = { a: '123', b: '123' } function checkP3(obj: p4): obj is p3 { return typeof (<p3>obj).a === 'string' ...

Understanding the significance of the term "this" in Typescript when employed as a function parameter

I came across a piece of TypeScript code where the keyword "this" is used as a parameter of a function. I'm curious to know the significance of this usage and why it is implemented like this in the following context: "brushended(this: SVGGElement) {". ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

How can we bring in a JavaScript file to an Angular 2 project?

I've been struggling with importing a JavaScript file into my Angular2 project. This particular file is not a module from npm, and the usual instructions using npm don't apply in this case. My setup involves using Angular CLI, and within my angu ...

Implementing a Map in Typescript that includes a generic type in the value

Here is a code snippet I am working with: class A<T> { constructor(public value: T) {} } const map = new Map(); map.set('a', new A('a')); map.set('b', new A(1)); const a = map.get('a'); const b = map.get(& ...

Obtaining attribute data value upon selection change in Angular 4

Having trouble retrieving the value from data-somedata in my code... <select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)"> <option *ngFor="let menu_optional of menu_optionals" value= ...

JavaScript cannot determine the length of an array of objects

I'm encountering an issue with an array of objects named tagTagfilter. When I log it in the browser, it doesn't immediately show the correct length value inside. tagTagFilter: TagFilter = { filterName: 'Tag', tags: [] ...

Vue/Vuex - Module two relies on module one, which in turn fetches data from the server

Take a look at this: import accountModule from '@/store/modules/account/account'; import otherModule from '@/store/modules/other/other'; export default new Vuex.Store({ modules: { account: accountModule, other: otherModule, ...

The TypeScript autocomplete feature is displaying two cars when I only need one

I am currently working with two props, one named car and the other named allStations. Whenever I press car, I am getting car.car as autocomplete, but I only want something like car.id, not car.car.id. Could someone please help me figure out what I am doi ...

Using TypeScript to pass objects to an arrow function

Issue at Hand: How do I successfully transfer an object from a parent component to a child component that is derived from the same interface? I am currently facing difficulties in rendering a list of tasks by looping through a list of task objects. The ma ...

I am encountering an issue with vue-router where I am finding it difficult to exclude certain words from the path regex

Currently facing an issue with vue-router where I need to exclude certain words such as: word1, some-word2, word3... from the router path { path: '/:pageIdenfifier(?!word1|some-word2|word3), name: 'SomePage', component: () =&g ...

Merge arrays with identical names within the same object into one cohesive object containing all elements

I just started using Vue and I'm not entirely sure if it's possible to achieve what I have in mind. Here is the structure I have: { "items":[ { "total":1287, "currency":"USD", "name":"string", "itemID":"", "pro ...

A guide on retrieving data from Firestore using TypeScript

I've been diving into a chat project using Angular, and Firestore has given me a bit of trouble. Trying to get the hang of typescript while working with it. Within app.module.ts, kicking things off with: import { provideFirebaseApp, getApp, initi ...

employ the keyof operator within a mapped type to generate an array containing the values in typescript

When working with TypeScript, it's easy to create a type-safe array of object keys like so: export type Keys<T> = [keyof T][]; export const keys = <T>(o: T): Keys<T> => Object.keys(o) as any; const k = keys(a); However, the ch ...

Encountering issues with the installation process of @vue/cli

Currently running Windows 7 with Node version 12.14.0 and npm version 6.13.4. I encounter the same error message shown in the image when attempting to install npm i @vue/cli -g, regardless of whether I use --bin-no-links or not. Can anyone offer some gui ...

Angular: Retrieving the Time Format from the Browser

Is there a way to retrieve the time format from the operating system or browser within Angular in order to display time in the user's preferred format? I have attempted to search for a solution, but have come up empty-handed. Thank you in advance! ...