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

Question about Typescript optional objects in interface

I am facing some issues with Typescript?

Suppose I have two interfaces defined, the second interface will use the first one as a type for its optional property of "link"

interface Link {
  href: string;
  text: string;
}

interface Container {
  id: number;
  link?: Link;
}

That is how I have it set up, however when I try to de-structure an Object that has the Container type

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

const {
  link:{
    href,
    text
   }
} = varOfTypeContainer

I get TypeScript warnings under both href and link
which state

"Property ‘href’ does not exist on type ‘Link | undefined’."

"Property ‘link’ does not exist on type ‘Link | undefined’."

How Could I fix this ?

>Solution :

As link is optional it means it could be undefined, and thus not holding href or text.

You need to discard that possibility before, then the compiler will know and will allow you to de-structure:

if(varOfTypeContainer.link !== undefined){
  const {
    link:{
      href,
      text
     }
  } = varOfTypeContainer;
  // ...
}
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