The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function.

However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function"

Below is the structure of the class and interface:

export interface Charge {
  code: string;
  name: string;

  getPrice: (category: string) => number;
}

export class StorePrice implements Charge {
  code: string;
  name: string;

  getPrice(category: string): number {
    return 234;
  }
}

The corresponding component is outlined below:

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  charges: Charge[];

  constructor() {
    this.charges = [
      {
        code: "125",
        name: "apple"
      } as StorePrice,
    ];
  }

  asStorePrice(charge: Charge) {
    return charge as StorePrice;
  }
}

Within the HTML file where the function is utilized:

<div>
  <div *ngFor="let charge of charges">

  {{asStorePrice(charge).getPrice()}}

  </div>
</div>

Answer №1

Here's the issue at hand:

this.charges = [
  {
    code: "125",
    name: "apple"
  } as StorePrice,
];

An alternative approach would be to instantiate an Object of StorePrice :

new StorePrice('125', 'apple');

like so:

export class StorePrice implements Charge {

  constructor(
      public code: string,
      public name: string
  ) {}

  getPrice(category: string): number {
    return 234;
  }
}

Answer №2

The issue lies in the usage of 'as'. 'as' is simply another way to cast an object.

<StorePrice> yourVariable;

When using 'as', it does not instantiate an object of the class. If you want to access the getPrice function on your object, you must instantiate the object in the usual way:

this.charges = [
  new StorePrice("125", "apple")
]

Naturally, you will also need to create a constructor within the class.

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

How can I determine the appropriate data type for 'this' when utilizing TypeScript in conjunction with DataTables?

I found some code on a page I visited: https://datatables.net/reference/api/columns().every() Here is the specific code snippet I am using: var table = $('#example').DataTable(); table.columns().every( function () { var that = this; ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

After restoring my Windows system, I encountered an issue with locating the typescript.js module for my Angular app development. I am currently troubleshooting the build

My PC had some issues, so I decided to restore Windows to an older restoration point. However, after doing this, I encountered an error while trying to build my Angular App: C:\Udemy\AngularDeCeroAExpertoEdicion2021\03-paisesApp>npm run ...

Changing the default component prefix in Angular to prevent TSLint warnings

When I create a new Angular 2 app with Angular CLI, the default component prefix is set to app-root for the AppComponent. However, if I decide to change the selector to something different like "abc-root", @Component({ selector: 'abc-root', ...

Validate multiple email addresses in a single input field, such as adding multiple recipients to the CC field in an email form using

Currently using Angular2 and primeng to create a basic email form with the following input fields: To: Cc: Message: Here is an excerpt of the code from my component class: constructor(private fb: FormBuilder) { this.createForm(); } createForm ...

Using InjectionToken within an Angular APP_INITIALIZER function

I am currently working on implementing an APP_INITIALIZER in my Angular 10 project. The factory function I'm using has multiple dependencies, one of which is an InjectionToken<string>. However, I have encountered an issue when trying to inject i ...

Using React to map and filter nested arrays while also removing duplicates

Hello, I recently started working with react and I've encountered a challenge while trying to map an array. const fullMen = LocationMenuStore.menuItems['menu']['headings'].map((headings: any) => { <Typography>{ ...

Is it possible to insert data into SQL Server from an Angular application without relying on .NET Core?

Is there a way to extract data from an Angular-made form and store it in a SQL Server table without the need for .NET Core? ...

When utilizing the package, an error occurs stating that Chart__default.default is not a constructor in chart.js

I have been working on a project that involves creating a package with a react chart component using chart.js. Everything runs smoothly when I debug the package in storybook. However, I encountered an error when bundling the package with rollup, referenc ...

Error in Vue 3 Script Setup with Typescript: Implicit 'any' type for parameter 'el' in Template ref

Could someone help explain why I am receiving an error from TypeScript that says the following? error TS7006: Parameter 'el' implicitly has an 'any' type. ref="(el) => saveRef(index, el)". I am confident that the correct type is set ...

ngFor returning undefined despite array containing value

While iterating through an array using ngFor, I'm encountering an issue where trying to access data in the 'value' variable results in it being undefined. Why is this happening? myArray = ['a', 'b', 'c', 'd ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

Can we guarantee that the key and its corresponding value are both identical strings in Typescript?

Is it possible to enforce the key of a Record to be the same as the inner name value in a large dataset? interface Person<T> { name: T title: string description: string } type People = Record<string, Person<string>> // example dat ...

Exploring the parent-child relationship of three components within Angular 2

Currently, I am developing a shopping cart using Angular 2. The application consists of two components - one for categories and another for product listings, both included in the main app component as children. However, I'm facing an issue where these ...

Tips for managing the outcome of an HTTP Post request

I am currently working with Angular 2 and Node.js, attempting to incorporate braintree into my project, which has proven to be quite challenging. My current approach involves utilizing an HTTP Post request to send back the result object from the transacti ...

"Encountering issue with auto-import suggestions failing to appear in VS Code version 1.88.0

After installing the necessary libraries for MUI, I encountered an issue where basic components like Typography were not showing up in intellisense. Instead, it was displaying @mui/icons-material. You can view screenshots below: https://i.stack.imgur.com/ ...

Tips for converting each item within an array into its own separate element

I currently have an array of objects that I am utilizing to generate a table in Angular. The table is functioning properly and successfully displays the data. However, I now have a requirement to enable editing for each individual object within the table. ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...