Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class:

export class ModuleInfoContainer extends Array<ModuleInfo>  {
  constructor() {
    super();
  }
  search(id: number) {
    let k: ModuleInfo;
    this.every(a => {
        k = a.search(id);
        return !k;
    });
    return k;
  }
}

Despite my expectations, during debugging I found that all array functions were accessible except for the member function search of ModuleInfoContainer. After some research online, I came across an example which led me to modify the code as follows:

export class ModuleInfoContainer extends Array<ModuleInfo>  {
  constructor() {
    super();
  }
search = function (id: number) {
    let k: ModuleInfo;
    this.every(a => {
        k = a.search(id);
        return !k;
    });
    return k;
  };
}

This modification resolved the issue and the code worked as anticipated.

What was wrong with the first code?

EDIT: ModuleInfo class

export class ModuleInfo {
  Id: number;
  Name: string;
  DisplayName: string;
  ChildModules: ModuleInfoContainer;
  DependsOn: ModuleInfo[];
  parent: ModuleInfo;
  search(id: number): ModuleInfo {
    if (this.Id === id) {
        return this;
    } else if (this.ChildModules && this.ChildModules.length) {
        return this.ChildModules.search(id);
    }
    return undefined;
  }
}

This is how I attempted to call the search function:

let k = new ModuleInfoContainer();
k.search(1);

The typescript compilation was successful, but at runtime, an error occurred stating that

k does not have a member function named search
(the error message might vary slightly, but the essence remains the same). However, the second code snippet worked correctly.

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

Converting an array into an object by using a shared property in each element of the array as the key

I have an item that looks like this: const obj = [ { link: "/home", title: "Home1" }, { link: "/about", title: "About2" }, { link: "/contact", title: "Contact1" } ] as const and I want to p ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

Applying Material UI class in React: Troubleshooting an error with your hook call

Recently, I have started using React and encountered an issue with a hook call. I understand the root cause of the problem but unsure how to resolve it without starting from scratch. Here is the snippet of the code: import { Fragment, PureComponent } from ...

What methods are available to prevent redundant types in Typescript?

Consider an enum scenario: enum AlertAction { RESET = "RESET", RESEND = "RESEND", EXPIRE = "EXPIRE", } We aim to generate various actions, illustrated below: type Action<T> = { type: T; payload: string; }; ty ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Error: The data type '(number | undefined)[]' cannot be converted to type 'number[]'

Transitioning to Typescript in my NextJS application has presented a challenge that I cannot seem to overcome. The error arises on the line value={value} within the <Slider.Root> The variable value comprises of two numeric elements: a min and a max. ...

The HttpInterceptor is programmed to identify and capture 401 error responses

After successfully implementing a code that called a logout() method upon receiving a 401 response from the server, I encountered issues following an upgrade of Angular from 5.2 to 7.0.3. It seems like either the HttpInterceptor interface has been modified ...

Implementing intelligent parameter type enforcement according to configuration settings

I can't decide on a name for this concept, so please be patient while I explain it. There are three configuration objects: const configA = { type: 'A' as const, getPath: (query: { foo: string }) => `/${query.foo}` } const config ...

Tips on resolving the 404 path error in Angular2/TypeScript ASP.NET 4.6.1 on Visual Studio 2015

I'm facing a challenge while developing a new application using TypeScript, Angular2, and ASP.NET 4.6.1 on VS2015. Two issues have come up in the process. First problem: I keep encountering 404 errors with the include files in my index.html file. Upo ...

An error occurred while trying to load the configuration "next/core-web-vitals" for extension

If you're embarking on a new project using NextJs and TypeScript, chances are you may encounter the following error: Failed to load config "next/core-web-vitals" to extend from. Wondering how to resolve this issue? ...

``There seems to be an issue with the Deno logger FileHandler as it

I am currently in the process of setting up loggers for an application. I have a handler named console which logs every event to the console. Additionally, there is a handler called app that is supposed to log all events to a file. While the logs are succ ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

What could be causing the rapid breakage of the socket in Ionic 3's Bluetooth Serial after just a short period

Although the code appears to be functioning correctly, it loses connection shortly after establishing it. This snippet contains the relevant code: import { Component } from '@angular/core'; import { Platform, NavController, ToastController, Ref ...

Managing the rxjs from an Array of observables when the array has no elements

Looking for a more elegant solution to handle the case where an array of observables is empty in the following TypeScript function. I want the observable to complete when subscribe() is called without the need for an initial check. I've already imple ...

What is the best way to assign a TypeScript type as the object type within an array of objects sourced from a different interface?

I am working with a generated interface that looks like this: export interface StaticPageLeftMenuV1 { id: string status: 'draft' | 'published' environments: ('dev' | 'staging' | 'production')[] ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

Error: The parameter should be a string, not an object

I am having trouble with a function that is supposed to return a string but instead, it returns an object. Unfortunately, I cannot use the .toString() method either. currentEnvironment: string = "beta"; serverURL: string = this.setServerURL(this.currentEnv ...

The NgModel function within *ngFor is executing more times than necessary during initialization

Displayed on screen are a list of tutorials with check boxes next to each tutorial's states. These tutorials and states are pulled from the database, each tutorial containing a name and an array of associated states. Here is the HTML code: <div c ...

Exporting a Middleware member is essential for defining Koa middleware type definitions

Currently utilizing KoA with Typescript and incorporating the KoA middleware KoA-static and KoA-bodyparser. Ensuring that I have installed the type definition packages @types/koa, @types/koa-bodyparser, and @types/koa-static. However, upon running tsc, enc ...

Atom-typescript does not always successfully compile all typescript files to JavaScript

Currently, I am in the process of learning how to implement routing in Angular2 by following a tutorial. The tutorial involves creating partial pages using .ts files along with companion .js files for each page. While my Atom editor, equipped with atom-typ ...