Skip to content

Restricting children to Specific Components in Svelte with TypeScript #16025

@OTheNonE

Description

@OTheNonE

Describe the problem

This is how you currently render the children within a component:

<!--my-component.svelte-->
<script lang="ts">
    import type { Snippet } from "svelte";

    type Props = {
        children?: Snippet
    }

    let { children }: Props = $props()

</script>

<div>
    My children are:
</div>

{@render children?.()}
<!--+page.svelte-->
<MyComponent>
  <p> Peter </p>
</MyComponent>

Although, using typescript, there is no way to define what the content of children within <MyComponent> should be.

Describe the proposed solution

I would like to define the type of children in the component, so that typescript only allows some specific elements or components to be children:

<!-- This should trigger an error in typescript. -->
<MyComponent>
  <p> Peter </p>
</MyComponent>

<!-- This should also trigger an error in typescript. -->
<MyComponent>
  <NotTheTypedComponentInMyComponent/>
</MyComponent>

<!-- This should be OK. -->
<MyComponent>
  <TheCorrectComponent/>
</MyComponent>

This should be done somehow similar to this:

<!--my-component.svelte-->
<script lang="ts">
    import MyComponent from "$lib/my-component.svelte"

    type Props = {
        children?: MyComponent // This does not work, but something similar to this.
    }

    let { children }: Props = $props()
    ...

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions