Last active
June 29, 2021 16:46
-
-
Save gomezcabo/378aef24f05dc685319a7da09d44fc3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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