Home > database >  Property 'isAdmin' does not exist on type 'User'.ngtsc(2339)
Property 'isAdmin' does not exist on type 'User'.ngtsc(2339)

Time:01-26

<td>{{ user.isAdmin }} &nbsp;&nbsp;&nbsp;&nbsp;</td>

I intended to add the isAdmin field with RxJS to the User interface, in the function down below (file is user.service.ts):

getUsers(): Observable<User[]>{
    return this.http.get<User[]>(`${this.apiUrl}/users`)
    .pipe(
      map(users => users.map(user => ({
        ...user,
        name: user.name.toUpperCase(),
        isAdmin: user.id === 10
      })))
    );
  }

The interface down below is the one used to process data (file is user.ts):

export interface User {

    id?: number;
    name: string;
    username: string;
    email: string;
    address: Address;
    phone: string;
    website: string;
    company: Company;
     
}

Since I apparently wrote it correctly, where else can the problem stem from and how can I solve it?

Thank you in advance!

CodePudding user response:

Its a pretty common pattern to enrich/modify your data received from your datasource with information needed in your application. That means the interface/type of the datastructure will change:

getUsers(): Observable<EnrichedUser[]>{
    return this.http.get<User[]>(`${this.apiUrl}/users`)
    .pipe(
      map(users => users.map(user => ({
        ...user,
        name: user.name.toUpperCase(),
        isAdmin: user.id === 10
      })))
    );
  }

export interface User {
    id?: number;
    name: string;
    username: string;
    email: string;
    address: Address;
    phone: string;
    website: string;
    company: Company;    
}

export interface EnrichedUser extends User {
  isAdmin: boolean;
}

In the map you convert the original User typed objects into EnrichedUser objects which have an additional property isAdmin. In this simple example the interfaces can extend from each other.

  • Related