Skip to content

Determine if empty, null or undefined children is passed #12675

@calvo-jp

Description

@calvo-jp

Describe the bug

Hi guys. Would like to know if this is an expected behavior of children in svelte 5. Given the code below
 

<!-- error-message.svelte -->
<script lang="ts">
  import type { SvelteHTMLElements } from 'svelte/elements';
  import { twMerge } from 'tailwind-merge';

  let { class: className, children, ...props }: SvelteHTMLElements['div'] = $props();
</script>

{#if children}
  <div
    class={twMerge('mt-1.5 block font-roboto text-xs text-[rgba(255,37,37,0.70)]', className)}
    {...props}
  >
    {@render children()}
  </div>
{/if}

<!-- login.svelte -->
<FormGroup>
  <FormLabel for="mobileNumber">Phone Number</FormLabel>
  <MobileNumberField id="mobileNumber" name="mobileNumber" placeholder="Enter Phone Number" />
  <ErrorMessage>{$errors.mobileNumber?.at(0)}</ErrorMessage>
</FormGroup>

We are expecting that when $errors.mobileNumber?.at(0) is undefined or null then #if children should return false but it instead returns true and renders the div. Is there a way to tell if an actual children (not undefined or null) was actually passed.

These get rendered because children is of type function

<ErrorMessage>{null}</ErrorMessage>
<ErrorMessage>{undefined}</ErrorMessage>

and this does not

<ErrorMessage></ErrorMessage>

Reproduction

<!-- error-message.svelte -->
<script lang="ts">
  import type { SvelteHTMLElements } from 'svelte/elements';
  import { twMerge } from 'tailwind-merge';

  let { children, ...props }: SvelteHTMLElements['div'] = $props();

  $inspect(Boolean(children));
</script>

{#if children}
  <div {...props}>
    {@render children()}
  </div>
{/if}

<!-- login.svelte -->
<ErrorMessage>{null}</ErrorMessage>
<ErrorMessage>{undefined}</ErrorMessage>
<ErrorMessage></ErrorMessage>

Logs

No response

System Info

Windows 11

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions