0

I'm working on an API written in Typescript 3.9.7 running on Node 10. I've removed unnecessary details, but I'm basically performing the following operations:

  1. Pulling user data from the database.
  2. Adding a 'state' field to each user object
  3. Sending the data to the UI.

I'm trying to use interfaces to add some type safety, but I seem to be misusing them since the TS compiler gives me some errors. Advice on how to resolve this would be helpful.

I've trimmed out other details, but here's my method where I fetch the user data and add the state field:

public async getUsers(
        parameter: string
    ): Promise<AugmentedUser[]> { 
    //return an array of User objects based on some parameter
    const userData = await this.userService.getAll<User>(parameter); 
    
    
    return userData.forEach((userRow: User) => {
           userRow.state = "inactive";
    });
}

and my interfaces are

export interface User {
    id: number;
    firstName: string;
    //some other fields
}

export interface AugmentedUser extends User {
    state: string;
}

I get the following error from the compiler:

error TS2322: Type 'UserData[]' is not assignable to type 'AugmentedUser[]'. Property 'state' is missing in type 'User' but required in type 'AugmentedUser'.

What am I doing wrong? I added the state field in the forEach loop so why am I getting this error? Thanks.

1 Answer 1

1

forEach does not return anything. Try the map function:

return userData.map((userRow: User) => {
  return {...userRow, state: 'inactive'};
});

This will generate a list of objects with all the User properties plus the state present in AugmentedUser.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.