Created
August 28, 2023 05:46
-
-
Save orion55/b261d8fba4aca0a32addca1a38ad90c9 to your computer and use it in GitHub Desktop.
ObjectManipulator
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
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 = {...this.obj}; | |
delete newObj[key]; | |
return new ObjectManipulator(newObj); | |
} | |
public getObject(): T { | |
return this.obj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment