0

I am trying to figure out why TypeScript is throwing an error in the styled component css file even though the type is obviously an object. Please see my code below:

export const OverlayCTA = styled.div<{
  ctaPosition?: object
}>`
  margin: 0.625rem 0 0;
  position: absolute;
  top: ${({ctaPosition}) => ctaPosition.top };
  left: ${({ctaPosition}) => ctaPosition.left };
  bottom:  ${({ctaPosition}) => ctaPosition.bottom };
  right:  ${({ctaPosition}) => ctaPosition.right };
  height: ${({ctaPosition}) => ctaPosition.height };
  @media (min-width: 992px) {
    margin: 3.375rem 0 0;
  }

ctaPosition is a prop containing an object that is passed from the component. As you can see, I declared the type as an object, however, I am getting the following error. Not sure why as it is an object type.

It is saying: Property 'height' does not exist on type 'object'.

enter image description here

Any help is appreciated. Thanks!

1 Answer 1

1

You need to provide the full details for the ctaPosition type because typescript does not know that height or the other keys exists in object.

you can define it above like

export type CtaPositionType = {
  top: string; //or number whichever it is
  left: string; //or number whichever it is
  bottom: string; //or number whichever it is
  right: string; //or number whichever it is
  height: string; //or number whichever it is
}

export const OverlayCTA = styled.div<{
  ctaPosition?: CtaPositionType
}>`
  margin: 0.625rem 0 0;
  position: absolute;
  top: ${({ctaPosition}) => ctaPosition.top };
  left: ${({ctaPosition}) => ctaPosition.left };
  bottom:  ${({ctaPosition}) => ctaPosition.bottom };
  right:  ${({ctaPosition}) => ctaPosition.right };
  height: ${({ctaPosition}) => ctaPosition.height };
  @media (min-width: 992px) {
    margin: 3.375rem 0 0;
  }

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Errors went away. Do you know if it is good practice to keep the type Object like that in the styled component file itself? @unhackit
If you are defining an object type with values, it is always good to define it's values like we did above. If you are too lazy to do so, you can use Record<any, any>, which says it's an object with any key and any value, and typescript will not shout at you. The only downside is that you will not get type suggestions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.