Static typescript constant

I'm working on implementing static readonly in my code, but I've never done anything like this before. Here's what I currently have:

export class Names {
    static readonly michael = { firstName: 'michael', secondName: 'jackson'};
    static readonly john = { firstName: 'John', secondName: 'Doo'};
    static readonly donald = { firstName: 'Donald', secondName: 'Trump'};
}

And I also have

name = 'michael';

What I want to achieve is to search within the Names class for a person named Michael and return their first and last name, similar to this:

found = { firstName: 'michael', secondName: 'jackson'};

For the sake of simplicity in explaining my question, let's assume all static readonly values are unique. I know how to search inside an array, but how do I search within a class?

Answer №1

If you need to access all the values stored in the Names object, you can utilize the Object.values method. From there, you can employ the find function to locate the specific value you are looking for:

Object.values(Names).find(person => person.name === 'michael')

Answer №2

Check out this example of Angular code:

import { Component, OnInit } from '@angular/core';
import { Names } from './models/Names';

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

export class AppComponent implements OnInit {

  title = 'angular-material';
  name = 'michael';

  constructor() { }

  ngOnInit(): void {
    if (Names[this.name]) {
      console.log(Names[this.name]);
    } else {
      console.log('Not found');
    }
  }
}

Answer №3

If you want to access a value by its label without converting to an array of objects and performing a linear search, there is a more efficient way:

export class Names {
    static readonly michael = { firstName: 'michael', secondName: 'jackson'};
    static readonly john = { firstName: 'John', secondName: 'Doo'};
    static readonly donald = { firstName: 'Donald', secondName: 'Trump'};
}

let name = 'michael';
let found = Names[name];
console.log(found);

However, TypeScript may flag this as inappropriate indexing by string for the Names type, which could be problematic with certain minifying compilers.

A better approach would be to use a different data structure, such as:

const names = {
  'michael': { firstName: 'michael', secondName: 'jackson' },
  'john': { firstName: 'John', secondName: 'Doo' },
  'donald': { firstName: 'Donald', secondName: 'Trump' },
};

This allows you to access values correctly using names[firstName]. It's also recommended to consider using a strictly-typed Map or representing your data with an actual class to prevent accidental modifications (e.g.,

names['donald'].secondName = 'duck'
).

Answer №4

To optimize your code, consider using a single static read-only variable that is an array holding all the objects you need. This essentially creates an array of objects. Here's how you can implement this in Angular:

import { Component, OnInit } from '@angular/core';
import { Names } from './models/Names';

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

export class Names implements OnInit {

  static readonly arrayOfObjects = [
    { firstName: 'michael', secondName: 'jackson'},
    { firstName: 'John', secondName: 'Doo'},
    { firstName: 'Donald', secondName: 'Trump'}
  ];

  constructor() {
    const filter = Names.arrayOfObjects.filter(object => object.firstName === 'michael');
  
    console.log(filter);
  }

}

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

The compatibility issue between Bootstrap and Angular 2 is causing some challenges

Hey there, I recently enrolled in an Angular 2 course on udemy and everything was running smoothly until I encountered an issue while trying to install bootstrap. I followed the installation steps diligently, but whenever I attempt to add any bootstrap el ...

Angular2 - Issue with Pagination functionality

When incorporating ng2-bootstrap as a pagination component, the guide provided at () made setting up the component a breeze for me. The pagination functionality is working smoothly and meeting my expectations. However, I've encountered an issue when ...

Error Encountered when Compiling Angular 4 Project with NPM Hosted Package: Understanding the 'makeDecorator' Issue

Since I began working on my two npm packages, I've been encountering this error that I can't seem to resolve. Every time I run ng serve, the error appears, but strangely disappears if I simply add a space and save the file (triggering an Angular- ...

Angular 4 RXJS Observable .interval() Fails to Execute in the Background

I have implemented a basic timer observable in my application that works fine. However, I noticed that when the tab is not active, the timer stops until I switch back to it. public timer = Observable .interval(100) Is there a way to keep the observable ...

What are the steps for launching an Angular application?

Running on ubuntu 18.0.4, I had angular-cli installed. Attempting to create a new app named conFusion using the command: ng new conFusion -dir=./conFusion --style=scss. CREATE conFusion/README.md (1026 bytes) CREATE conFusion/angular.json (3666 by ...

The element 'imgAreaSelect' does not appear to be valid in this context

I came across an example, but it is not specifically for Angular. I attempted to create a project in angular 6 involving image area selection, but encountered the following error: .component.ts(64,16): error TS2339: Property 'imgAreaSelect' do ...

Nested RxJS subscribe with error handling actions

I have a block of code that contains nested subscribe calls: this.http.post('/update1', newData).subscribe( (response) => { const r = response.json; const id = r['id']; this.http.post('/update2?id=&a ...

Having trouble uploading a PNG image (logo) with Cypress

I have been attempting to upload a png file using Cypress and here is what I have tried so far: Cypress.Commands.add('upload_image', (fileName, selector) => { return cy.get(selector).then(subject => { return cy.fixture(fileName, &apo ...

Pattern for defining objects with indexes in Typescript

My data is structured as shown below: let equipment:Equipment = { "1": { "name": "abc", "data": 123 }, "2": { "name": "def", "data": 234 }, "3": { "name": "ghi", "data": 345 }, ... } Converting this into an array se ...

Issues have arisen with Angular 7.2.15 and three.js 0.105.2 following the upgrade of three.js

After updating Angular from V-7.2.5 to V-7.2.15 and Three.js from V-0.101.2 to V-0.105.2, I encountered a myriad of errors that I'm struggling to resolve: THREE.Box3's method .getSize() is throwing "error TS2554: Expected 1 arguments, but got 0. ...

Issue with updating the div to show the user's submission form in Angular is causing difficulties

After a user submits a form, I would like to display their submission by hiding the form area and showing the response in that same area. Upon submitting the form, my goal is to show a mat-spinner until a response is received from the server. The compone ...

Elevating Material-UI Drawer using makeStyles to a whole new level with styled-components

Currently working on a React app using TypeScript, Material-UI, and styled-components. While incorporating a SideDrawer with Material-UI Drawer component, I am transitioning my code from makeStyles to styled-components for easier maintenance. How ...

calculating the dynamic height of a document from top to bottom using Angular

Is there a way to dynamically calculate the height of each page from top to bottom in Angular? The syntax that works in JavaScript seems to give an error in Angular. console.log( (document.height !== undefined) ? document.height : document.body.offsetHeigh ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Issue with SvelteKit: PageData not being refreshed in API response after initial render

I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a tag. However, I am facing an ...

Troubleshooting TS2769 Issue with Protect Middleware in Express.js

When trying to secure routes on an Express server, I attempted to simplify my middleware, but I continue to encounter an error: src/routes/userRoutes.ts:10:19 - error TS2769: No overload matches this call. The last overload gave the following error. Argum ...

What strategies work well when it comes to developing translation files in Angular?

Currently, I am involved in a front-end project using Angular. For translation implementation, I am looking for the most effective approach to creating translation files. Instead of having a file per language, I am considering creating a translation file f ...

Exploring the options variables within CLI commander Js action

As a newcomer to developing CLI apps, I've chosen to work with ts-node and commander. However, I'm currently facing a challenge in understanding how to access the options that users pass into my command action. program .version(version) .nam ...

Error: Unable to initialize mock worker: "The module './pdf.worker.js' could not be located using 'pdfjs-dist' in a Next.js and TypeScript environment."

I've been attempting to utilize the 'pdfjs-dist' package in order to extract text from a pdf file stored in my AWS S3 bucket. However, when I execute the code, I encounter the following error: Error: Setting up fake worker failed: "Cann ...

Create an array with individual key-type pairs for each generic element, then iterate through the array

Consider the enum and type declarations in the code below: enum MyEnum { FIRST, SECOND }; type MyType = { firstKey: string | null, secondKey: boolean, thirdKey: MyEnum } Next, a variable is declared using the type as follows: let glob ...