I am creating a simple component that accepts an optional prop but also accepts arbitrary props to pass through to it's sub-components, however I can't get this combination to play nicely together. I've modified the sample from here as an example: Typescript3 Release Notes
import React from 'react';
export interface Props {
name: string;
[id: string]: any; // <-- Added to allow acceptance of arbitrary props
}
export class Greet extends React.Component<Props> {
render() {
const { name, ...divProps } = this.props;
return <div {...divProps}>Hello {name.toUpperCase()}!</div>;
}
static defaultProps = { name: 'world' };
}
Usage:
<Greet />
As soon as I add in the option to have arbitrary props, I get the following error
Property 'name' is missing in type '{}' but required in type 'Readonly<Props>'.
My questions are:
1) Is there any known way to accept arbitrary props and have defaultProps work?
2) Is this a good (is there better?) way to accept arbitrary props?
If you have the props defined for the inner component you can intersect (&) them together so then you'll have type safety on all of your props.
type Props = {
name: string;
}
type InnerCompProps = {
color: string,
}
const InnerComp = (props: InnerCompProps) => (<div> the color is { props.color} </div>);
export class Greet extends React.Component<Props & InnerCompProps> {
static defaultProps = { name: 'world' };
render() {
const { name, ...rest } = this.props;
return <InnerComp {...rest} />;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With