David
David

Reputation: 560

Typescript React. Destruct and spread object

Trying keep my child components stateless (functional components). So, I'm looking for convenient way of allocating root component state values to its children components. Say,

interface IState {
  a: string;
  b: number;
  c: (e) => void;
}

then

<ChildA {...this.state as { a: string, c }} />
<ChildB {...this.state as { c: (e) => void, b }} />

Unfortunately TypeScript does not currently support shorthand property names. Is there any elegant approach here?

Upvotes: 1

Views: 823

Answers (1)

Leone
Leone

Reputation: 3418

In the latest typescript versions you can use the spread operator as you put above without the need to cast ... as long as you have the right prop types for your child components.

Assuming ChildA component has props like:

interface ChildAProps {
    a: string;
    c: (e) => void;
}

To define the child stateless component use:

const ChildA : React.SFC<ChildAProps> = props =>
    <div>{this.props.a}</div>

React.SFC is alias for React.StatelessComponent class. And later to use an instance of ChildA inside the parent component with state, just write:

<ChildA {...this.state} />

Upvotes: 1

Related Questions