0

I want to create a matching function which takes a subset of the classes property values and checks if they are matched against the given parameters.

The Problem: how can I dynamically access the property values of the instance by using the data from the function parameter? is there a better fitting type than Pick for this?

Later on I want to move matches to a superclass, so I cannot check on the props manually.

//Example implementation
class Person {
    public readonly name: string;
    public readonly mail: string;
    public readonly age: number;

    constructor(name: string, mail: string, age: number){
        this.name = name;
        this.mail = mail;
        this.age = age;
    }

    public matches(params: Pick<Person, keyof Person>): boolean {
        //??? something like:
        for(let param of params){
            if(this[param.key] !== param.val) return false;
        }
        return true;
    }
}

//Example usage.
let p: Person = new Person("me", "me@mail", 69);

let mat = p.matches({name: "me", mail: "me@mail"});
console.log(mat);```

Thanks.

1 Answer 1

1

You want Partial :

public matches(params: Partial<Person>): boolean {
    return !Object.entries(params).some(([k, v]) => {
      return this[k as keyof Person] !== v;
    })
  }

Object.entries has a downside though, the key return has a type string, hence the type assertion.

Playground

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

Comments

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.