David David - 1 year ago 235
TypeScript Question

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;


<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?

Answer Source

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 =>

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} />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download