Skip to content

Instantly share code, notes, and snippets.

@toanbku
Last active May 16, 2024 02:57
Show Gist options
  • Save toanbku/da02d1cdd6166a896d76ba3d65d9e07f to your computer and use it in GitHub Desktop.
Save toanbku/da02d1cdd6166a896d76ba3d65d9e07f to your computer and use it in GitHub Desktop.
Rename key of object in TypeScript while keeping the object immutable
export function renameKey<T extends object, K extends keyof T, N extends string>(
obj: T,
oldProp: K,
newProp: N
): Omit<T, K> & { [P in N]: T[K] } {
const { [oldProp]: oldValue, ...rest } = obj;
return {
...rest,
[newProp]: oldValue,
} as Omit<T, K> & { [P in N]: T[K] };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment