Skip to content

Instantly share code, notes, and snippets.

@gomezcabo
Last active June 29, 2021 16:46
Show Gist options
  • Save gomezcabo/378aef24f05dc685319a7da09d44fc3d to your computer and use it in GitHub Desktop.
Save gomezcabo/378aef24f05dc685319a7da09d44fc3d to your computer and use it in GitHub Desktop.
/*
https://typescript-exercises.github.io/#exercise=15&file=%2Findex.ts
export class ObjectManipulator {
constructor(protected obj) {}
public set(key, value) {
return new ObjectManipulator({...this.obj, [key]: value});
}
public get(key) {
return this.obj[key];
}
public delete(key) {
const newObj = {...this.obj};
delete newObj[key];
return new ObjectManipulator(newObj);
}
public getObject() {
return this.obj;
}
}
*/
type ObjectWithNewProp<T, K extends string, V> = T & {[NK in K]: V};
export class ObjectManipulator<T> {
constructor(protected obj: T) {}
public set<K extends string, V>(key: K, value: V): ObjectManipulator<ObjectWithNewProp<T, K, V>> {
return new ObjectManipulator({...this.obj, [key]: value} as ObjectWithNewProp<T, K, V>);
}
public get<K extends keyof T>(key: K): T[K] {
return this.obj[key];
}
public delete<K extends keyof T>(key: K): ObjectManipulator<Omit<T, K>> {
const newObj: T = {...this.obj};
delete newObj[key];
return new ObjectManipulator(newObj);
}
public getObject(): T {
return this.obj;
}
}
const obj1 = new ObjectManipulator({ a: 1, b: 2})
const obj2 = obj1.set('c', 'tres')
const obj3 = obj2.delete('a')
obj1.get('c') // Error, obj1 does not contain key 'c'
obj2.get('c') // Correct
obj3.get('a') // Error, obj3 does not contain key 'a'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment