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
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;
// ...
}