-
Notifications
You must be signed in to change notification settings - Fork 12.8k
[discussion] dynamic merge properties to type(or interface) by its specific key #28041
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
My thoughts: type PropsOfHtmlTag<T extends keyof React.ReactHTML> =
React.ReactHTML[T] extends React.DetailedHTMLFactory<infer R, any>
? R
: never
interface ButtonProps {
component: keyof React.ReactHTML
}
type DynamicProps = PropsOfHtmlTag<ButtonProps['component']> What we need is to merge |
I think this is possible: import * as React from "React";
type AttributesForTag = { [K in keyof React.ReactHTML]: React.ReactHTML[K] extends React.DetailedHTMLFactory<infer Attr, any> ? Attr : never; };
class Button<K extends keyof AttributesForTag> extends React.Component<{ component: K } & AttributesForTag[K]> {
render() {
const { component, ...rest } = this.props as any;
return React.createElement(component, rest);
}
}
const x = <Button component="button" type="submit" /> Is it also possible to just make the element be one of the props? class Button2 extends React.Component<{ component: JSX.Element }> {
render() { return this.props.component; }
}
<Button2 component={<button type="submit" />} /> |
@Andy-MS Thanks for your response. I tried your example in VSCode: Since HTML tag Seems it merges all HTML tags' attributes? Then we got multiple definitions |
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 acomponent
prop, and will use this value as component actually rendered. Its implementation may looks like this:we need native HTML element's props merged to
ButtonProps
.For example, the usage examples below should be all type safe.
Which means, if
component === 'a'
,ButtonProps
should beif
component === 'input'
,ButtonProps
should beHow to figure this out in TypeScript?
The text was updated successfully, but these errors were encountered: