Skip to content

[discussion] dynamic merge properties to type(or interface) by its specific key #28041

Closed
@pd4d10

Description

@pd4d10

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: JSX/TSXRelates to the JSX parser and emitterQuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions