TypeScript workaround for rest props in React
You probably can't avoid creating a new object with a subset of the properties of this.props
, but you can do that with type safety.
For example:
interface LinkProps {
textToDisplay: string;
}
const LinkPropsKeys: LinkProps = { textToDisplay: "" };
class Link extends React.Component<LinkProps & React.HTMLAttributes, {}> {
public render(): JSX.Element {
return (
<a { ...this.getHtmlProps() }>{ this.props.textToDisplay }</a>
);
}
private getHtmlProps(): React.HTMLAttributes {
let htmlProps = {} as React.HTMLAttributes;
for (let key in this.props) {
if (!(LinkPropsKeys as any)[key]) {
htmlProps[key] = this.props[key];
}
}
return htmlProps;
}
}
Using LinkPropsKeys
object, which needs to match the LinkProps
, will help you keep the keys between the interface and the runtime lookup synchronized.
It's actually easier than all of the answers above. You just need to follow the example below:
type Props = {
id: number,
name: string;
// All other props
[x:string]: any;
}
const MyComponent:React.FC<Props> = props => {
// Any property passed to the component will be accessible here
}
Hope this helps.