Skip to content

Instantly share code, notes, and snippets.

@sh1989
Last active October 20, 2019 21:33
Show Gist options
  • Save sh1989/a86a34a003d9f0175b24cfabae84fe4b to your computer and use it in GitHub Desktop.
Save sh1989/a86a34a003d9f0175b24cfabae84fe4b to your computer and use it in GitHub Desktop.
TypeScript safe React props and default props merge

Given an interface definition for a property:

interface MyProps {
  foo: string,
  bar: string
}

And a partial declaring some default props

const defaultProps: Partial<MyProps> {
  foo: "baz"
}

Rather than having to merge the properties manually in a functional React component (which doesn't seem to give you any type information)...

const render = (props: MyProps) => {
  const safeProps = {...defaultProps, ...props};
}

You can create a generic utility mergeProps function to do this for you, with a type that can be inferred!

function mergeProps<T>(defaultProps: Partial<T>, props: T): T {
  return {...defaultProps, ...props};
}

Which can be called as such:

const render = (props: MyProps) => {
  const safeProps = mergeProps(defaultProps, props);
}

In VSCode, IntelliSense will now correctly see safeProps : MyProps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment