Using Typescript, develop a function within an entity to verify the value of a property

In my Angular 7 app, I have an entity defined in my typescript file as follows:

export class FeedbackType {
    id: number;
    name: String;
}

I am looking to create a function within this entity that checks the value of a property. For example:

feedbackType.IsGreat();

After some research, I attempted the following:

export class FeedbackType {
    id: number;
    name: String;

    public isGreat() {
        return this.name === 'Great';
    }
}

However, I encountered the following error:

feedbackType.isGreat is not a function


This concept is akin to the method seen in C#:

public static bool IsGreat(this FeedbackType feedbackType)
{
    return feedbackType.name == "Great";
}

Answer №1

A simple method to accomplish this task

class ExperienceType {
    constructor(private id: number, private title: string) {}
    isPositive() { return this.title === 'Positive'; };
}

Here's how you can implement it:

let et: ExperienceType = new ExperienceType(0, 'Positive');
if (et.isPositive()) {
   //perform actions
}

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

What is the best method to include spacing between strings in an array and then combine them into a csv-friendly format?

The method I am currently employing involves the following: var authorsNameList = authors.map(x => x.FirstName + ' ' + x.LastName); Yet, this generates an outcome similar to this: Bob Smith,Bill Jones,Nancy Smith Nevertheless, the desired ...

Testing the React context value with React testing library- accessing the context value before the render() function is executed

In my code, there is a ModalProvider that contains an internal state managed by useState to control the visibility of the modal. I'm facing a dilemma as I prefer not to pass a value directly into the provider. While the functionality works as expecte ...

Utilizing Type Script 1.8 with Visual Studio 2017 for older projects: A step-by-step guide

After installing Visual Studio 2017, I encountered a TypeScript error when trying to run my project. It seems that VS 2017 is using TypeScript 2.1.5, while my application was designed for TypeScript 1.8. Is there a way to make VS 17 utilize TypeScript 1.8 ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

Using the scrollIntoView method on an element with a height of 0 within an Angular 2+ application

I am currently working with the following HTML code snippet: <div class="row-20 st-margin" *ngIf="role == 'Administrator'" id="hr-data"> <div class="col-md-12"></div> </div> After ...

What is the process of importing types in TypeScript?

Here is the export I am working with: import * as jwt from 'jsonwebtoken'; ... export type MyJsonWebToken = typeof jwt; Next, when attempting to use it in my code: export class AuthService { constructor( @Inject(constants.JWT) private ...

What kind of impact on performance can be expected when using index.ts in a Typescript - Ionic App?

When setting up the structure of a standard Ionic app, it typically looks like this: app pages ----page1 ---------page1.ts ----page2 ---------page2.ts If I were to include an index.ts file in the pages folder as follows: pages/index.ts export { Page1 } ...

Shattered raw emotion

Does anyone have any insight on how to resolve this error? I've hit a roadblock trying to figure out the issue in the message below. Here is the snippet of code: :label="` ${$t('cadastros.clientes.edit.status')}: ${cliente.status === ...

Tips for displaying the default keyboard with numbers and symbols on Ionic applications

Is there a way to display a keyboard like the image provided by default in an Ionic5 app for Android? I attempted using type="number", but it restricts input to numbers only. However, on iOS, the full keyboard is displayed with this type. When I ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...

Troubleshooting error messages in Angular related to scss ModuleBuild

I've been working on applying a theme to my Angular application, but I've run into an issue. It seems that the src/theme.scss file I created is functioning correctly on its own. However, when I try to import "~@angular/material/theming", I encoun ...

Error: While working in an Angular project, a TypeError occurs because the property '****' cannot be read when used within a forEach loop

As I attempt to iterate over this.data.members and perform certain actions within the forEach loop on this.addedUsers, I encounter a TypeError: Cannot read property 'addedUsers' of undefined. Interestingly, I can access this.data.members outside ...

Unable to load the PDF file in Angular 8 due to an error

I've been attempting to display a PDF in a new browser tab using Angular 8. The PDF is retrieved from a Spring Boot API as a byte array: @GetMapping(value = "/pdf") public ResponseEntity<byte[]> beve(HttpServletRequest request) { return new ...

Issues with connecting to server through Angular websocket communication

I deployed the server on an Amazon AWS virtual machine with a public IP address of 3.14.250.84. I attempted to access it using Angular frontend like so: public establishWebSocketConnection(port : number){ this.webSocket = new WebSocket('ws://3.14.250. ...

Combining various FormGroup types into a single object type in Angular 5

I am currently utilizing the mat-stepper feature from the Angular Material design library. Within my application, I am using 3 separate FormGroups to gather information and send it to a database using the httpClient method. To achieve this, I have defined ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Is it possible to construct an Angular project without altering the file size limit?

The budget of 40.00 kB fell short by 60.66 kB for a total of 80.66 kB. I've been grappling with the issue of exceeding the max file limit for anyComponentStyle. While working with Material UI and utilizing indigo-pink.css in my component scss, I&apo ...

Angular failing to retrieve URL parameters correctly

As I was trying to retrieve URL queries like www.website.com?a:b, I decided to follow the guidance provided in a particular Angular tutorial. This official tutorial (accessible via this link) instructed me to implement the following simple code snippet wit ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

Error: The archived-solution-list.component.html file failed to load due to an unhandled Promise rejection

I am encountering the following error on the console while executing my code. Just so you know, everything was working fine before a minor modification. I would appreciate your assistance in resolving this: Unhandled Promise rejection: Failed to load ar ...