Home > other >  Accessing class property dynamically in typescript
Accessing class property dynamically in typescript

Time:10-07

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.

CodePudding user response:

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

  • Related