Skip to content

Instantly share code, notes, and snippets.

@mdesantis
Last active July 30, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdesantis/2d6dbf620779e64a4ee279342b9e252d to your computer and use it in GitHub Desktop.
Save mdesantis/2d6dbf620779e64a4ee279342b9e252d to your computer and use it in GitHub Desktop.
TypeScript: function that extends an object with a dynamic key
// 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