Search code examples
angulartypescriptstrict

Angular 11 strict mode how do you compare the to objects by property in a loop


I have am trying to upgrade a library to version 11, strict mode. The code can be found here works when strict is not enforced and in prior version of angular. https://stackblitz.com/edit/angular-ivy-fsnmjo?file=src%2Fapp%2Fmodel%2Fmember.ts. I have defined a method in the Member class to determine if 2 objects are "equal".

In my application, a member is equal if some of the properties match up.

I have tried two different approaches to solve the problem, "equalsV1" and "equalsV2".

equalsV1 produces the following error.

Error in src/app/model/member.ts (17:17) Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Member'. No index signature with a parameter of type 'string' was found on type 'Member'.

equalsV2 produces the following error:

Error in src/app/model/member.ts (32:17) Type 'Extract<keyof this, string>' cannot be used to index type 'Member'.

My question is how do you compare the to objects by property without explicitly citing each property, i.e. memberTocompare.id === this.id is not an acceptable answer.


Solution

  • The answer was to change the following:

    if (memberToCompare[key] !== value) {
                    return false;
                }
    

    to

    if ((memberToCompare as any)[key] !== value) {
                    return false;
                }
    

    I got the clue for Thayne's answer to Element implicitly has an 'any' type because type 'Window' has no index signature?

    My complete code answer is here https://stackblitz.com/edit/angular-ivy-2tjpxr?file=src%2Fapp%2Fmodel%2Fmember.ts

    If any one has a better solution I would love to see it.