#Property does not exist on type

1 messages · Page 1 of 1 (latest)

sand ember
#

I'm running into this TS error in a SvelteKit project. I suspect the issue is that the .find that is returning the typed data may also return undefined, but I don't know how to handle this issue in a way that works with TS.

The code:

    // Content
    let {title, panelTitle, panelContent, background} = data.content.find(
        (content) => content.language === $page.params.lang
    );

The TS error:

Property 'title' does not exist on type '{ language: string; title: string; panelContent: string; panelTitle: string; background?: string | undefined; } | undefined'.ts(2339

Thanks for any insights you can provide!

vague blade
#

check if its not undefined before destructuring

sand ember
#

Is there an easy way to do that and retain type information & still use destructuring? This is what I tried, and obviously the types get lost (data and content are both typed otherwise):

    // Content
    let content = data.content.find(
        (content) => content.language === $page.params.lang
    );

    let title, panelTitle, panelContent, background;
    
    if (content) {
        ({title, panelTitle, panelContent, background} = content);
    }
vague blade
#
const content = data.content.find(
  (content) => content.language === $page.params.lang
);
if (content) {
  const { title, panelTitle, panelContent, background } = content;
  // rest of code
}
sand ember
#

I'm not sure that is viable with sveltekit in a +page.svelte context, with the variables scoped to the IF they are then not available outside of the script block

burnt jewel
#

maybe something like this:

let {title, panelTitle, panelContent, background} = data.content.find(
    (content) => content.language === $page.params.lang
) ?? {};

that'll make title etc be X | undefined, which i think is what you want?