Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 3, React defaultProps, and passthrough props

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?

like image 746
FrozenKiwi Avatar asked May 12 '26 19:05

FrozenKiwi


1 Answers

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} />;
  }
}
like image 62
Josh Avatar answered May 15 '26 08:05

Josh