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

Time:12-16

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:

(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?

CodePudding user response:

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

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

CodePudding user response:

const film: { 
              title: string | null | undefined,
              director: string | null | undefined 
             } = await getEvent({ id });

Your variable when declared, should have a name (film) and then it follows the type of the variable after :

  • Related