Accessing properties in Angular/TypeScript: extracting values from a partially extended interface

I am fairly new to Angular/TS and I may not have worded this correctly, but I will do my best to explain.

I have defined 2 interfaces where one extends the other as shown below:

export interface CustomerModel {
   firstName: string;
   lastName: string;
    //other things
}

export interface OrderModel extends Pick<CustomerModel, 'firstName' | 'lastName'> {
  orderNumber: number;
}

I have created a service with a hardcoded instance of Customer (currently working locally on my machine and using hardcoded data. I plan to integrate a database later, but need it to function in this manner initially)

export class CustomerService {
  customers: CustomerModel[];
  constructor() {
    this.customers = [{
     firstName: 'John',
     lastName: 'Doe',
    //more here 
       },
{
     firstName: 'Jane',
     lastName: 'Smith',
    //more here 
       },
     ]
   }

   getCustomers(): Observable<CustomerModel[]> {
    const customers = of(this.customers);
    return customers;
 }
}

Now I am attempting to create an Order Service utilizing the OrderModel

export class OrderService {
  orders: OrderModel[];
  constructor() {
    this.orders = [{
     orderNumber: 123;
     firstName: ???, //what should I use here to extract the name from CustomerModel
     lastName: ???,
       },
     { 
    //more here 
       },
     ]
   }

   getOrders(): Observable<OrderModel[]> {
    const orders = of(this.orders);
    return orders;
 }
}

When examining the value of firstName in my OrderService, it indicates that it is derived from CustomerModel, confirming that the extension was successful.
If I omit firstName and lastName from the orders array, I receive an error stating that OrderModel expects them. Perhaps this approach is not feasible and there might be a better solution, but I have been stuck trying to make this work. Could someone assist me in retrieving the values of the properties firstName/lastName from CustomerModel?

Answer №1

To optimize your code in this scenario, it's recommended to create a separate file that stores the base data for the user and then manipulate it as necessary later on.

// app/some-folder/customers.ts
export const customers: CustomerModel[] = [
  {
    firstName: 'John',
    lastName: 'Doe',
    //more here 
  },
  {
    firstName: 'Jane',
    lastName: 'Smith',
    //more here 
  },
];

Within the service:

import { customers } from '@app/some-folder/customers.ts'

export class CustomerService {

  public getCustomers(): Observable<CustomerModel[]> {
    return of(customers);
  }

}
import { customers } from '@app/some-folder/customers.ts'

// Transform existing customers by adding an orderNumber
// Use ...a, orderNumber: i to combine customer data with orderNumber
const orders: OrderModel[] = customers.map((a, i) => ({
  firstName: a.firstName,
  lastName: a.lastName,
  orderNumber: i,
}))

// Alternatively, structure orders to include customerId or customer object as per API response format
// const orders = customers.map((a, i) => ({ customer: a, orderNumber: i }))


export class OrderService {

  public getOrders(): Observable<OrderModel[]> {
    return of(orders);
  }

}

This approach simplifies API implementation by allowing easy swapping of function bodies.

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

Indicate the location of tsconfig.json file when setting up Cypress

Having trouble integrating Cypress with Typescript? I've encountered an issue where Cypress is unable to locate the tsconfig.json file I created for it. My preference is to organize my project with a custom directory structure, keeping configuration f ...

Tips for incorporating the closeAutocomplete function into ng4-geoautocomplete

Hey there! I've incorporated the ng4-autocomplete component into my custom component and now I'm trying to figure out how to detect when the autocomplete dropdown closes. Can you help me out with implementing the "closeAutocomplete" method? Let& ...

Node.js serves an Angular application without the need for additional JavaScript scripts

After developing an Angular application with a node.js server, I encountered an issue where the browser displayed the HTML code served by the server as text instead of rendering the web page correctly. This problem arose when I built the Angular project in ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

The error message "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: The file extension ".ts" is not recognized for the file located at /Project/src/index

Whenever I run npm run dev, I keep encountering the following error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Project/src/index.ts. Despite having all my settings configured as recommended, Here is a snippet of my package ...

Getting access to a child component function within the UI-VIEW in Angular 2

I am working on a project that involves both angular 1.5 and angular 2. In my project, I have two sibling components: First-component and Second-component. The First-component contains a Toggle button, while the Second-component has a UI-View of angular 1. ...

Tips on utilizing array filtering in TypeScript by solely relying on index rather than element callback

When running tslint, I encountered the following error message: https://i.sstatic.net/p2W9D.png Is it possible to filter based on array index without utilizing element callback? Any alternative suggestions would be appreciated. ...

Angular 4 - Issue with Top Navigation Bar not remaining fixed at the top of the page

I'm having trouble finding a solution to keep the top navigation bar fixed at the top of the screen without allowing it to scroll when the page becomes too long. I want to prevent the top nav bar from scrolling and maintain its position at the top of ...

Tips for Clearing Previous Information Windows When Clicking on a Different Marker in Google Maps Using Ionic/Angular

Is there a method to remove the previous Info Window when clicking on another marker in Google Maps using Ionic/Angular? ...

Issue with Bootstrap 4 component styling in Angular 4 application test

I am working on creating a test application using Angular 4 and have successfully installed Bootstrap 4 for Angular as instructed on https://ng-bootstrap.github.io/#/getting-started. I have included Bootstrap in the main module and in my basic navbar menu ...

real-time mat-progress-bar constantly updating

Is it possible to have the progress bar updated in real-time without having to reload the page every time? <mat-progress-bar *ngIf="row.stage === 'importing_in_progress'" class="exchange-files__progress-bar" mode=&quo ...

Utilizing Tick formatting in Chart.js with Typescript: A step-by-step guide

When setting Chart.js to use the en-US locale, the scale numbers are formatted optimally. https://i.sstatic.net/fzjpQmM6.png If I try using a tick callback as shown in the documentation: ticks: { callback: function(value) { return value.toStr ...

While attempting to utilize npm install, I encounter an error on a discord bot stating "msvsVersion is not defined."

Struggling with self-hosting a TypeScript discord bot, the setup process has been a puzzle. It's supposed to generate a build directory with an index.js file, but it's unclear. Installed Visual Studio Build Tools 2017 as required, yet running npm ...

The KendoTreeView embedded within a Kendo Grid table

I am looking to implement the kendoTreeViewCheckable feature for each node in my KendoTreeList. Is there a way to incorporate KendoTreeView within a Kendo Grid Table similar to how KendoTreeList functions? https://i.sstatic.net/UL2b0.png ...

Retrieving data from a nested JSON array using AngularJS

I am struggling to navigate the intricate nested tree view of child items within a JSON array. I have been grappling with this challenge for days, trying to figure out how to access multiple children from the complex JSON structure. Can someone provide g ...

I'm encountering an error while trying to build my Ag-Grid using npm run build, can someone help me figure out

Being relatively new to Next.js and web development in general, my background mainly consists of working with compiled languages. I recently embarked on a project to build a web app using Ag-Grid, drawing inspiration from an example I found on a public Git ...

Is it necessary to unsubscribe from multiple switchmaps?

Consider the following scenario: Should I implement an unsubscribe in each instance of switchMap? And is it necessary to include a takeUntil after every switchMap operation? this.sharedSrv.postDetail.pipe( switchMap(post => { if (post) { th ...

Error: Model function not defined as a constructor in TypeScript, mongoose, and express

Can anyone help me with this error message "TypeError: PartyModel is not a constructor"? I've tried some solutions, but now I'm getting another error as well. After using const { ... } = require("./model/..."), I'm seeing "TypeError: C ...

When implementing angular routing, the default route is not automatically selected

When using routerLinkActive for selecting the default route and displaying an image, I encountered an issue where the image was not loading upon initial page load. However, when I switched tabs, the image would display correctly. Below is the code snippet ...