Typescript generic methods to access and set the values of properties of a class instance
Typescript generic methods to access and set the values of properties of a class instance
When we are using repository pattern to implement an application in TypeScript, it is always a necessity to update an entity partially and pass this to repository for processing. For this we can use the below code
class User {
private name;
constructor(name) {
this.name = name;
}
get getName() {
return this.name;
}
set setName(name) {
this.name = name;
}
}
const userObj = new User('Scott');
console.log(userObj.getName); // "Scott"
userObj.setName = 'Tiger';
console.log(userObj.getName); // "Tiger"
The above boilerplate is perfect if we have only a couple of object properties. What to do if we have many properties and required keep their types as well. Then we can use TypeScript generics to achieve this requirement. Please look into the below code how we have achieved this.
In the below code we have added two methods
prop
to access the value of a propertysetProp
to set the value of a property
Please check the method generic definition for more.
type UserData = {
id?: number | null;
name: string;
email: string;
ssn: string;
dob: string;
address: string;
};
class User {
private id?: number | null = null;
private name: string;
private email: string;
private ssn: string;
private dob: string;
private address: string;
constructor({ name, email, ssn, dob, address, id }: UserData) {
this.name = name;
this.email = email;
this.ssn = ssn;
this.dob = dob;
this.address = address;
id && (this.id = id);
}
prop<K extends keyof UserData>(prop: keyof UserData): UserData[K] {
return this[prop] as UserData[K];
}
setProp<K extends keyof UserData>(
prop: keyof UserData,
value: UserData[K]
): void {
Object.assign(this, { [prop]: value });
}
}
// example
const user = new User({
name: 'Vimson Varghese',
email: 'vimson@gmail.com',
ssn: '123-45-6789',
dob: '01-01-1990',
address: '37 Elstree Road, Birmngham',
});
expect(user.prop('name')).toBe('Vimson Varghese');
user.setProp('id', 10);
expect(user.prop('id')).toBe(10);