Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use TypeScript props keys for function component props

I have this code for example:

interface Props {
  children: any,
  className?: string,
  marginTop?: number,
  marginBottom?: number,
}

const Div = styled.div`
  ${(props: Props) => { return css`
      flex:1;
      ${props.marginTop && "margin-top: " + props.marginTop + "px;"};
      ${props.marginBottom && "margin-bottom: " + props.marginBottom + "px;"};
    `; 
  }}
`;


export const Column: React.FC<Props> = ({ children, className marginTop, marginBottom }) => {
  return (
    <Div className={className} marginBottom={marginBottom} marginTop={marginTop}>
      {children}
    </Div>
  );
};

Now I have to declare the props twice, once in Props and once in the exported component.

Is there a way to make all defined Props available as props for the component?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Just to make it clear, this is the part I’m trying to save my self to write again:

({ children, className marginTop, marginBottom })

>Solution :

If you need to have access to all props (such as passing all of them down to a child component or a styled component), then as what Jon suggested: do not destructure them as arguments. Instead, you can destructure it in the function body instead, if that is what makes you feel makes your code a little more readable:

export const Column: React.FC<Props> = (props) => {
  const { children } = props;
  return (
    <Div className="Column" {...props}>
      {children}
    </Div>
  );
};

This is no different than the old school way:

export const Column: React.FC<Props> = (props) => {
  return (
    <Div className="Column" {...props}>
      {props.children}
    </Div>
  );
};

p/s: For the purpose of typing, it might make sense to define the props type directly on your styled component, i.e. const Div = styled.div<Props>:

const Div = styled.div<Props>`
  ${(props) => { return css`
      flex:1;
      ${props.marginTop && "margin-top: " + props.marginTop + "px;"};
      ${props.marginBottom && "margin-bottom: " + props.marginBottom + "px;"};
    `; 
  }}
`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading