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

Property which can be null or undefined causing "does not exist" error

I’m trying to figure out the correct way to destructure a returned object.

Here is the TypeScript code:

const id = 1;
const { film: { title, director } } = await getEvent({ id });

I get an error under both title and director:
Property does not exist on type film.
When I hover over film, it shows the 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

(property) film?: {
    title?: string | null | undefined;
    director?: string | null | undefined;
    ... and 10 more ...;
} | undefined

How can I tell the compiler that these properties do exist without changing the type of title and director to not be undefined/null/optional?

>Solution :

You can make the TypeScript compiler happy by supplying default values:

const { film: { title = '', director = '' } = {} } = await getEvent({ id });
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