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

Remove every other element from a JSON Array by splicing out the even-numbered items, rather than removing matching items

After receiving a JSON Array Output from a REST API, I am using ng-repeat to display the items on an HTML page. The structure of the received data is as follows: var searchresponse = [{ "items": [{ "employeeId": "ABC", "type": "D", "alive": "Y ...

Is there a way to find the recursive key types in TypeScript?

Is there a method to ensure that code like this can compile while maintaining type safety? type ComplexObject = { primitive1: boolean; complex: { primitive2: string; primitive3: boolean; } }; interface MyReference { myKey: keyof ComplexObj ...

Connecting two fields with a line on click in AngularJS

In the top section, there are 10 fields and in the bottom section, there are another 10 fields. I want to be able to connect two fields with a line when they are clicked (one from the top section and one from the bottom section). This connection should app ...

Eslint is back and it's cracking down on unused variables with no

I've configured eslint to alert me about unused variables rules: { '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }], } Presently, I have a TypeScript class structured like this: import { User } from &ap ...

"I am having trouble with AngularJS - the ng-disabled directive is not working as expected

I'm attempting to conceal an option based on a certain condition, but the option still remains visible. Below is the code I am using: <li role="presentation"><a role="menuitem" tabindex="-1" ng-disabled="di ...

Saving a boolean value and a number to Firestore in an Angular application

In my Angular 5 typescript project, I have a form with various input fields and selections. Here is how I am capturing the form values: let locked: boolean = (<HTMLInputElement>document.getElementById("locked")).value; let maxPlayers: number = (& ...

When using @Viewchild, it can sometimes lead to encountering

Within my project, I have a component called SideToggleComponent that contains a function: activeButton(value){ ... } I am trying to call this function from another component called BlogComponent. To do so, I am using @ViewChild as shown below: @ ...

Searching for an AngularJS and Bootstrap Dual Listbox Solution

I need a component like this to integrate into my project: I am hoping to add it using npm. However, I have tried some of the examples available but faced issues (encountered exceptions or only found bower instead of npm). The following are the examples ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

After downloading the quickstart (angularjs2) from angular.io, I encountered an error when trying to start npm

[email protected] typing start G:\quickstart\quickstart-master tsc && concurrently "tsc -w" "lite-server" [1] 'lite-server' is not recognized as a valid command, [1] executable program or batch file. [1] lite-serve ...

Utilize AngularJS to retrieve and interact with the JSON data stored in a local file once it has

Please do not mark this as a duplicate since I have not found a solution yet. Any help would be appreciated. I have a file called category.json located next to my index.html file, containing the following JSON data: [{"name":"veg"},{"name","non-veg"}] W ...

Unable to locate a compatible version for caniuse-lite with the specified range of ^1.0.30001349

I encountered an error while running npm install: npm ERR! code ETARGET npm ERR! notarget No matching version found for caniuse-lite@^1.0.30001349. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a package v ...

Angular background image not displayed

After searching extensively, I came across many examples that didn't work for me. I'm not sure what I'm doing wrong and I need assistance! I noticed that I can see the image if I use the <img> tag, but not when I try to set it as a ba ...

By implementing a custom function within the router's "redirectTo" method, we can dynamically determine the destination for redirection, effectively avoiding Ahead-of-Time (A

By implementing a function to decide where the user should be directed when the site loads, I encounter the following challenge: { path : '', redirectTo: redirector(), pathMatch: 'full' } The redirector() function returns a rout ...

Steps to duplicate the package.json to the dist or build directory while executing the TypeScript compiler (tsc)

I am facing an issue with my TypeScript React component and the package.json file when transpiling it to es5 using tsc. The package.json file does not get copied automatically to the dist folder, as shown in the provided screenshot. I had to manually copy ...

Reactive form within a form

I am working on an angular application that involves a nested reactive form. I would appreciate it if you could review my method of nesting the form by passing the parent form reference in the child component and let me know if this approach is appropria ...

Challenges with Angular directive scopes

My current task involves taking an existing template and Angularizing it. I am dealing with 3 directives: a card, a card-header, and a card-body: <card> <card-header title="My Card"> <input type="text" ng-model="userSearch" /&g ...

Leveraging vue-devtools in combination with the composition-api while implementing a render function (such as JSX)

Ever since I made the transition to utilizing the composition-api and incorporating a render function (primarily leveraging JSX with TypeScript for type safety within the template), I've encountered an issue where vue-devtools cannot inspect the compu ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Encountering a problem when attempting to open a model dialog in AngularJS

I'm looking to implement a modal dialog in my project, but I seem to be encountering some issues. Here's what my HTML code looks like: <div ng-controller="bodyController"> <!-- This html would live at the path specified in the contr ...