Last active
May 16, 2024 02:57
-
-
Save toanbku/da02d1cdd6166a896d76ba3d65d9e07f to your computer and use it in GitHub Desktop.
Rename key of object in TypeScript while keeping the object immutable
This file contains 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
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