Home > Software engineering >  Typescript and destructured variables not recognising props
Typescript and destructured variables not recognising props

Time:05-12

I have a function that returns data. The object that gets returned contains headerMenu, page, content and footer. These are all returned as objects of which all of this is defined in DataProps

With the line const { headerMenu, page: { content }, footer }: DataProps = data Its throwing an error saying that Type '{}' is missing the following properties from type 'DataProps': headerMenu, page, content, footer

But we can see the props are defined here? What am I missing here or can we not use destructuring in TS

Full component code below

type IndexProps = {
  postData: object,
  preview: boolean,
}

type PreviewSubscriptionProps = {
  data: object,
}

type DataProps = {
  headerMenu: object,
  page: object,
  content: object,
  footer: object,
}

export default function Index({ postData, preview } : IndexProps) {
  const router = useRouter();
  
  const {data} : PreviewSubscriptionProps = usePreviewSubscription(HomepageGroq, {
    initialData: postData,
    enabled: preview || router.query.preview !== undefined,
  });

  const { headerMenu, page: { content }, footer }: DataProps = data

  return (
    <>
      <SiteHeader headerMenu={headerMenu} />

      <Content content={content} />

      <SiteFooter footer={footer} />
    </>
  );
}```

CodePudding user response:

PreviewSubscriptionProps has a key data of object type.

type PreviewSubscriptionProps = {
  data: object,
}

In TS, object type is used to represent just a non primitive type. It is not a string,number,boolean etc. But, it is not guaranteed to have any key.

A min repro example

 const {data} : PreviewSubscriptionProps = ...
 const { headerMenu, page: { content }, footer }: DataProps = data

In the above statement you try to destructure the data key. But data is just of object type. Hence you get the error.

You can use any instead of object if you are not sure about the keys. Read more

Further, you will also face an issue here:

const { headerMenu, page: { content }, footer }: DataProps = data

The above means you are trying to extract content key from page. You would want to extract like this:

const { headerMenu, page, content , footer }: DataProps = data

CodePudding user response:

PreviewSubscriptionProps type does not all the keys of DataProps type fix that and you are destructuring like this const { headerMenu, page: { content }, footer }: DataProps = data but your DataProps type has been defined like

type DataProps = {
  headerMenu: object,
  page: object,
  content: object,
  footer: object,
}

content is not in an page. Fix this also. Either destructure like this const { headerMenu, page, content, footer }: DataProps = data or modify DataProps type.

  • Related