I have a component that takes one fixed prop and one that can be random. When it comes to typing the component, I’d want to play it type safe and avoid just using any for the addition props. Here’s what I have in mind:
App.tsx:
<Button component='button' href='x'>
Push Me
</Button>
Button.tsx:
import { type PropsWithChildren, type ElementType, type FC } from 'react';
interface ButtonProps {
component: ElementType;
[key: string]: any;
}
export const Button: FC<PropsWithChildren<ButtonProps>> = ({
component: Component,
children,
...props
}) => {
return <Component {...props}>{children}</Component>;
};
How can I remove the any from [key: string] and infer the additional props?
2
Answers
give a try to following .
and let me know if any ?
If nesting the props under an object is allowed, then this works pretty well:
If nesting under an object is not an option then I think you can’t get full type safety. I’ve tried hacking at it for a while with mostly no luck. It seems typescript isn’t really great at validating
Omit
spread types haha.