What is the best way to invoke a class function within a static object?

Here's an example for you:

export class MyClass {
  myString: string;

  constructor(s: string) {
    this.myString = s;
  }

  myFunction() {
    return "hello " + this.myString;
  }
}

export class MainComponent {

  static object1: MyClass = JSON.parse(`{"myString":"1234"}`);

  MainComponent.object1.myFunction(); // Error: myFunction is not a function
}

The issue arises because the function member is not recognized in the static object. I'm receiving an error: myFunction is not a function

Answer №1

What is your goal with this approach? It doesn't seem to relate to any practical use that I can think of. Are you just experimenting with TypeScript? It's hard to imagine how a function could magically appear from a JSON.parse call that only contains an object :)?

But, if you really want to make that function work, you could try modifying your code like this:

class cls1{
  str1:string;

  constructor(s:string){
    this.str1 = s;
  }

  func1(){
    alert(this.str1);
  }
}

class AppComponent  {

   static obj2:cls1= new cls1(JSON.parse('{"str1":"efgh"}').str1);
}

AppComponent.obj2.func1(); // alert: 'efgh'

Check out this jsFiddle

Let's set aside the coding style issues for now and continue on your coding journey :)

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

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

What is the reason behind Angular's repeat filter only being able to access its own element within the return function?

I have successfully implemented some Angular code that is working, however, I am struggling to understand why it works. Coming from a C Sharp background and being new to JS and Typescript. <tr ng-repeat="colleague in Model.FilteredColleagueListModel | ...

Modal for Firestore CRUD operations update()

Currently seeking assistance with a CRUD system that involves modal dialogues. I have successfully implemented adding and deleting functionalities, but I am encountering an issue with editing. Although I can retrieve the data for each record in its respect ...

Tips for bundling a substantial Typescript framework using Webpack

In my endeavor to construct a TypeScript framework and bundle it using Webpack, I have encountered a perplexing issue. The problem lies in determining the appropriate "entry point" - setting it to all files results in only the final built file being access ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

When a block reaches a certain height, the mat-chip-list in Angular Material is automatically shortened to fit. This feature is exclusive to

<div fxFlex="100" fxFlex.gt-sm="80" fxFlex.sm="100"> <div *ngFor="let permission of arrayOfObjectPermissions; let index = z" class="permissions-list"> <mat-card [title]=&qu ...

What methods can I use to dismantle an Angular component?

I have created a modal as a component called <modal-component>. Within the <modal-component>, there is a close button. I am looking for a way to completely remove the <modal-component> when this close button is clicked. I envision somet ...

Issue when transferring properties of a component to a component constructed Using LoadingButton MUI

Check out my new component created with the LoadingButton MUI: view image description here I'm having issues passing props to my component: view image description here Dealing with a TypeScript problem here: view image description here I can resolv ...

Step-by-step guide to initializing data within a service during bootstrap in Angular2 version RC4

In this scenario, I have two services injected and I need to ensure that some data, like a base URL, is passed to the first service so that all subsequent services can access it. Below is my root component: export class AppCmp { constructor (private h ...

Steps for creating an observable array using a Firestore DocumentReference array field

I am in the process of organizing a firestore database specifically for e-commerce functions. At the moment, I have a main collection for products and another for users. The users collection includes an array field named cart where I store DocumentReferenc ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

Experiencing a "HEROES not found" error while following an Angular guide

I've been diving into Angular with the tutorial provided on https://angular.io. However, I've hit a roadblock at step 4. Displaying a list where I'm encountering an error in HeroesComponent. Cannot find name 'HEROES' The cod ...

The correlation between methods in programming languages

Can a class or object be created with type constraints between methods? abstract class Example<T>{ abstract methodOne(): T abstract methodTwo (arg: T):any } I am looking to ensure that the argument of methodTwo is the same type as the return ty ...

Exploring Angular 2 - examining how @input is implemented within the ngOnInit lifecycle hook for testing a component

Presently, I am facing a challenge while attempting to test a child component that is designed to receive input from the host component and utilizes the ngOnInit lifecycle hook as depicted in the following code snippet. @Component({ selector: 'my ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

Stop accidental form submissions on iOS devices by disabling the return button

In my Ionic 3 application running on iOS, I encountered a bug that allows users to submit a form even when the submit button is disabled. Despite trying different solutions from this source, I have not been successful in resolving it. To prevent accidenta ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Conceal when clicking away from specified angular 4 element

I have developed a vertical navigation menu with a side menu that toggles open and closed on click. The issue I am facing is that I need to close the side menu when clicking anywhere outside of it. To address this, I attempted to use a solution from this G ...