Closed
Description
Actually it is a question, but I think it may refers to type system of TypeScript, so I post it here.
The problem is how to dynamic merge properties to type(or interface) by its specific key.
Assuming we are creating a React component named Button
. It takes a component
prop, and will use this value as component actually rendered. Its implementation may looks like this:
interface ButtonProps {
component: keyof React.ReactHTML
}
class Button extends React.Component<ButtonProps> {
render() {
const { component: Component, ...rest } = this.props
// give it a button style
// `component`'s value could be button, a, input, etc
return <Component {...rest} />
}
}
we need native HTML element's props merged to ButtonProps
.
For example, the usage examples below should be all type safe.
<Button component="button" type="submit">A Button</a>
<Button component="a" href="/">A Link Button</a>
<Button component="input" type="submit" value="An input button" />
Which means, if component === 'a'
, ButtonProps
should be
{ component: React.ReactHTML } & React.AnchorHTMLAttributes<HTMLAnchorElement>
if component === 'input'
, ButtonProps
should be
{ component: React.ReactHTML } & React.InputHTMLAttributes<HTMLInputElement>
How to figure this out in TypeScript?