Last active
July 30, 2021 15:40
-
-
Save mdesantis/2d6dbf620779e64a4ee279342b9e252d to your computer and use it in GitHub Desktop.
TypeScript: function that extends an object with a dynamic key
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
// TS Playground link: https://tsplay.dev/wRJl5w | |
interface Props { | |
baseKey: string | |
} | |
const withCustomKey = <K extends string>(customKey: K) => { | |
return <P>(props: P): P & { [k in K]: boolean } => { | |
return { ...props, [customKey]: true } as P & { [k in K]: boolean } | |
} | |
} | |
const myProps: Props = { 'baseKey': 'some value' } | |
const myPropsWithCustomProperty = withCustomKey('customInjectedKey')(myProps) | |
console.log(myPropsWithCustomProperty.baseKey) | |
console.log(myPropsWithCustomProperty.customInjectedKey) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment