1

having

userGroups: IUserGroup[];
this.service.getUserGroups().subscribe(g => this.userGroups = g);

getUserGroups returns IUserDifferentGroup[] but both IUserGroup and IUserDifferentGroup have the same fields additionally IUserGroup have some more, how to map response to new type ?

interface IUserDifferentGroup{
    Name: string;
    Code: string;
    Id: number;
}

interface IUserGroup {
    Id: number;
    GroupName: string;
    Visible: boolean;
    IsDefault: boolean;
    CanAssociated: boolean;
}

1 Answer 1

3

Use this inside subscribe,

this.service.getUserGroups().subscribe(g => this.userGroups = g as IUserGroup[]);

EDIT

As per the comments, modifying,

interface IUserDifferentGroup {
    Name: string;
    Code?: string; // <-- made this optional
    Id: number;
}

interface IUserGroup {
    Id: number;
    GroupName: string;
    Visible: boolean;
    IsDefault: boolean;
    CanAssociated: boolean;
}

then change subscribe to,

this.service.getUserGroups().map((g) => return {Name: g.GroupName, Id: g.Id})
 .subscribe(g => {
  this.userGroups = g as IUserGroup[];
});

See if it fixes it.

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

5 Comments

I got that one type is not compatible with other, to be honest the IUserGroup has the same what IUserDifferentGroup but also 2 more fields
I see. Please show both types, in order to see the difference
If you can make the 2 more fields present in IUserGroup optional by using the elvis-operator ? to those properties in its interface definition.
First of all, they are not same. In interfaces, the property names do matter as well as its types. I can see Id and Name maps to Id and GroupName. What does Code which is of type string map to in the other interface? (the rest of the properties there are booleans)
I would like to just map Id and name to GroupName

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.