Skip to content

Instantly share code, notes, and snippets.

@orion55
Created August 28, 2023 05:46
Show Gist options
  • Save orion55/b261d8fba4aca0a32addca1a38ad90c9 to your computer and use it in GitHub Desktop.
Save orion55/b261d8fba4aca0a32addca1a38ad90c9 to your computer and use it in GitHub Desktop.
ObjectManipulator
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