What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like:

function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c}
// undefined
b = new a(1,2)
// a {foo: 1, bar: 2, yep: 3}

However, I've been struggling to achieve the same in TypeScript. None of the following approaches seem to work:

class A {
    foo: number;
    bar: number;
    yep: foo + bar;
}

class A {
    foo: number;
    bar: number;
    yep: this.foo + this.bar;
}

class A {
    foo: number;
    bar: number;
    let yep:number = this.foo + this.bar;
}

class A {
    foo: number;
    bar: number;
    yep: number;

    constructor() {
        this.yep = this.foo + this.bar;
    }
}

class A {
    foo: number;
    bar: number;

    get yep(): number {
        return this.foo + this.bar;
    }
}

class A {
    foo: number;
    bar: number;
    yep: function () {return this.get("foo") + this.get("bar")};
}

I tried initializing it as follows:

somevar: A = {
    foo: 1,
    bar: 2
}

Additionally, I experimented with this approach:

somevar: A = {
    foo: 1,
    bar: 2,
    this.yep: this.foo + this.bar
}

Your assistance on resolving this matter is greatly appreciated. The complexity of the calculation requires a more efficient solution that can be reused without embedding it directly into the template.

Answer №1

Here is an illustration of a TypeScript class featuring a calculated property:

class Human {
    firstName: string;
    lastName: string;
    fullName: string;

    constructor (firstName: string,  lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.fullName = firstName + ' ' + lastName;
    }
}

let individual = new Human('Alice', 'Smith');
console.log(individual.fullName); // => Alice Smith

Another example utilizing the getter:

class Individual {
    firstName: string;
    lastName: string;

    constructor (firstName: string,  lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    get fullName(): string {
        return this.firstName + ' ' + this.lastName;
    }
}

let person1: Individual = new Individual('Bob', 'Johnson');
console.log(person1.fullName); // => Bob Johnson

Answer №2

X represents a category rather than an interface, requiring the creation of an instance. Merely assigning an object literal will not suffice. The 'shape' must not only be compatible but also match an instance of the category.

Any variables defined as private, protected, or public within the constructor will become part of the category.

For instance:

class X {
  public attribute: number;

  constructor(
      public parameter1: number,
      public parameter2: number
  ) {
        this.attribute = parameter1 + parameter2; 
    }
}

const x: X = new X(3, 5);

Answer №3

For those who prefer organizing it as a class:

class B {
    x: number;
    y: number;
    z: number;
    constructor(a: number, b: number) {
        this.x = a;
        this.y = b;
        this.z = a * b;
    }
    // include getter or setter methods
}

let instance = new B(3, 4);

Answer №4

Give this a shot:

class MyClass {
    constructor() {
        this.myVar = 100;
    }
    
    getMyValue() {
        return this.myVar;
    }
}

const myInstance = new MyClass();
myInstance.getMyValue();

Answer №5

A different approach.

Type safety remains intact when utilizing Object.assign in this manner.

It's important to note that without the explicit use of strictNullChecks (highly recommended), TypeScript will default to considering undefined | null as assignable to any type.

interface IA {
  foo: number;
  bar: number;
}

class BaseClass {
  constructor(obj: IA) {
    if (obj) Object.assign(this, obj);
  }
}

class A extends BaseClass implements IA {
  public foo: number;
  public bar: number;

  constructor(obj: IA) {
    super(obj);
  }

  public get yep(): number {
    return this.foo + this.bar;
  }
}

const somevar: A = new A({
  foo: 1,
  bar: 2,
})

console.log(somevar)

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

Unable to retrieve form data like the username from my AngularJS controller

I am having trouble implementing the registration functionality to save user details from a form to the database. When trying to access the username in my controller, I keep getting an undefined error. username is:undefined signup.controller.js (13,9) ...

AngularJS - How to loop through a div to display all items

I am working with AngularJS to create a repeatable shopping cart items feature. Below is a sample JSON data structure: [{"src": "img/T1.jpg", "itemname": "solid green cotton tshirt", "style": "MS13KT1906", "colour": "Blue", "size": "s", "qty": "1", "price ...

Executing Grunt: Setting up a dual Connect and Express server to operate on one port

I'm still fairly new to Grunt and I've been wondering if it's possible to run both servers on the same port simultaneously. I seem to be encountering some issues with this setup, most likely stemming from the Grunt file. I am utilizing grun ...

Using the original type's keys to index a mapped type

I am currently developing a function that is responsible for parsing a CSV file and returning an array of objects with specified types. Here is a snippet of the code: type KeyToTransformerLookup<T> = { [K in keyof T as T[K] extends string ? never : ...

AngularJS in action for a new Widget Framework

I am working on a project that requires creating a page similar to iGoogle. This page will consist of various drag-and-drop widgets, with each widget representing a distinct application. Does anyone have any advice or recommended links for this type of pr ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Handling a callback after the completion of another action in Angular 2

I am facing an issue where I need to delete an item from a list and then update the page to reflect that change. The current code handles the deletion of the item using DELETE_APPLICATION and then fetches the updated list using GET_INSIGHT_APPLICATIONS. Ho ...

Identifying data types in arrays using TypeScript type predicates

My current approach involves a function that validates if a variable is an object and not null: function isRecord(input: any): input is Record<string, any> { return input !== null && typeof input === 'object'; } This type predica ...

An error has occurred in Angular2 and Ionic 2, where there is a TypeError preventing the reading of the property 'addEventListener' in the InAppBrowser

When attempting to open a remote address in my app using the Cordova plugin InAppBrowser, I encountered an issue with the following code: import { Injectable } from "@angular/core"; import { HttpQueryService } from "./httpqueryservice"; import { ToastCo ...

How can I arrange the ng-class based on the clicked item's order?

http://plnkr.co/edit/pUtuZy?p=preview In this scenario, there are three different border classes available: .border1 { border: 1px solid #66FFFF; } .border2 { border: 1px solid #33CCFF; } .border3 { border: 1px solid #0099FF; } The goal is to as ...

Utilizing ngClassEven and ngClassOdd in Angular 2 for Improved Styling

I attempted to replicate the behavior of ng-class-even and ng-class-odd (originally from Angular 1) in my Angular 2 application. Below is the code I wrote and it's functioning correctly, but I'm curious if there are alternative methods to achiev ...

A DropdownListFor with a predefined value using ng-model

I am currently working on creating a DropdownList using the code snippet below. However, I am facing an issue where the default text "Select Product/Program..." is not being set in the dropdown. Strangely, when I remove the ng-model, it works correctly. Do ...

Updating Dropdown Selection in Angular 9 and 10

Is there a way to set attributes to "Selected" in HTML options based on a condition from a *ngFor loop in response.body of the component ts file? Below is the dropdown code: <select [(ngModel)]="customer.id"> <option *ngFor="let location of lo ...

Assigning a value to the ng-model in AngularJs based on the user's selection from a Dropdown Menu

I tried to utilize a drop-down Selection to assign the model of the Search Box based on user selection: ng-model=searchText.$ (For search across Any of the 3 fields) ng-model=searchText.name (For search only on name field) ng-model=searchText.age (For s ...

What is the process for creating custom event bindings in AngularJS?

There is a custom event called core-transitionend (specifically triggered by Polymer), and I am able to specify an event handler using document.addEventListener(). However, what would be the most recommended approach for achieving this in AngularJS? Alter ...

Is it possible for me to add a string to a URL as long as the string is not null?

When retrieving data from a database, I have the option to include specific parts for a more targeted search. Let's say I have an object structured like this: { title: "wonderland", aliases: "", ... } My goal now is to generate a URL for the ...

Expanding a piece of Bootstrap within an Angular project results in exceeding the "budget" during CI/CD implementation

I have incorporated Bootstrap into my Angular project. In order to streamline my code, I replaced the Bootstrap mt-4 class with form-item for elements wrapping form controls, labels, and validation messages. I then defined the styling for these items in th ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

sending a collection of image data arrays wrapped in FormField objects from Angular to Express

I am facing a challenge while trying to upload two FormField objects along with form data to express. I am having trouble using the multer library in express to extract this data from the request. While I can access the form data, the FormField objects re ...

Enhancing data validation and converting strings to dates with Nest.js - DTO approach

Anticipating the upcoming request to adhere to the ISO 8601 standard timestamp format, something similar to "2023-12-04T15:30:00Z" (typically embedded as a string within JSON data that needs conversion to a JavaScript Date object). This is my Data Transfe ...