Home > Back-end >  Use TypeScript props keys for function component props
Use TypeScript props keys for function component props

Time:02-22

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?

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

({ children, className marginTop, marginBottom })

CodePudding user response:

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;"};
    `; 
  }}
`;
  • Related