Typescript: 'gridTemplateColumns' is specified more than once, so this usage will be overwritten.ts(2783)

I upgraded my typescript version from 4.0.5 to 4.9.5 in my react project.

In the following code (styled components):

export const __offerBlock: IStyles = (props: any) => ({
  gridTemplateColumns: "18% auto",
  ...(props.isMobile
    ? {
        margin: "0 15px",
        gridTemplateColumns: "10% auto"
      }
    : {
        width: "98%"
      })
});

I’m getting this error:

'gridTemplateColumns' is specified more than once, so this usage will be overwritten.ts(2783)
__fileNameStyles.ts(158, 3): This spread always overwrites this property.

enter image description here

How do I allow typescript to allow overwrite using spread?
Also, why is the error coming when I’m conditionally adding the "gridTemplateColumns" property.

This error only started after bumping up the ts version.

>Solution :

You can just move the outer gridTemplateColumns into the else clause of the ternary:

export const __offerBlock: IStyles = (props: any) => ({
  ...(props.isMobile
    ? {
        margin: "0 15px",
        gridTemplateColumns: "10% auto"
      }
    : {
        width: "98%",
        gridTemplateColumns: "18% auto"
      })
});

However, while I’m at it, might I suggest that you change this even further? What you are basically doing here is returning one of two different literal objects, so you can just write your function like that instead:

export const __offerBlock: IStyles = (props: any) => {
  if (props.isMobile) {
    return {
      margin: "0 15px",
      gridTemplateColumns: "10% auto"
    }
  } else {
    return {
      width: "98%",
      gridTemplateColumns: "18% auto"
    }
  }
}

Leave a Reply