Cast from `Type | undefined`

Hi everyone. I'm trying to show a data from Sanity CMS, using createAsync:
const data = createAsync(() => getProject(params.slug));
const data = createAsync(() => getProject(params.slug));
But the problem is, any way to cast dat() to my Type removing the Type | undefined? Because currently the ProjectHeroSection is complain because the data() could be undefined, but at this point I know that isn't undefined.
<Show when={!!data()}>
<ProjectHeroSection
title={data()?.title}
headline={data()?.headline}
thumbnail={data()?.thumbnail}
/>
</Show>
<Show when={!!data()}>
<ProjectHeroSection
title={data()?.title}
headline={data()?.headline}
thumbnail={data()?.thumbnail}
/>
</Show>
Anyone can help me please?
6 Replies
Brendan
Brendan5mo ago
This is sort of just normal really. Typescript has no way to know that your Show component means that other calls to data() will always have a value. Since you know better, you can assert the value is non-null if you want to (with ! instead of ?):
<ProjectHeroSection
title={data()!.title}a
headline={data()!.headline}
thumbnail={data()!.thumbnail}
/>
<ProjectHeroSection
title={data()!.title}a
headline={data()!.headline}
thumbnail={data()!.thumbnail}
/>
Daniel Sousa @TutoDS
but any way to assert the value to non-null for the entire component (inside the Show)?
Madaxen86
Madaxen865mo ago
Sure. Show provides also a callback for children which provides the value of the truthy when condition. So you should remove the double “!!“:
<Show when={data()}>
{(post) => <ProjectHeroSection
title={post().title}
headline={post().headline}
thumbnail={post().thumbnail}
/>
</Show>
<Show when={data()}>
{(post) => <ProjectHeroSection
title={post().title}
headline={post().headline}
thumbnail={post().thumbnail}
/>
</Show>
There’s also a keyed prop for show which turns the callback value into a store like object. See last example in the docs: https://docs.solidjs.com/reference/components/show
Daniel Sousa @TutoDS
Thanks and sorry for the noob questions
Madaxen86
Madaxen865mo ago
Your welcome. No need to be sorry ☺️
Daniel Sousa @TutoDS
For some reason, the value on the callback isn't a accessor but the value itself Sorry, now I understand the usage of keyed property
Want results from more Discord servers?
Add your server