Skip to content

Instantly share code, notes, and snippets.

@mdesantis
Last active July 30, 2021 15:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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