Skip to content

Instantly share code, notes, and snippets.

@mdesantis
Last active Jul 30, 2021
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