Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How do you type check injected child component in svelte?

$
0
0

I was wondering if you could do a type check on a child component that is injected into a parent component in Svelte?

So for example, if I wanted to do the following, but where the child is only allow to be of the type of the ChildRight component and not of another component like ChildWrong.

I have researched a little and concluded that you can either use <slot> or <svelte: component> to inject another component. A solution to either method would be useful.

Using slot

Parent.svelte

<div style="width: 500px; height: 500px; background-color: red;"><slot></slot></div>

App.svelte

<script>    import Parent from "./Parent.svelte"    import ChildRight from "./Child-right.svelte"    import ChildWrong from "./Child-wrong.svelte"</script><Parent><ChildRight /></Parent>

Using svelte:

Parent.svelte

<script lang=ts>    export let childElement;</script><div style="width: 500px; height: 500px; background-color: red;"><svelte:component this={childElement} /></div>

App.svelte

<script>    import Parent from "./Parent.svelte"    import ChildRight from "./Child-right.svelte"    import ChildWrong from "./Child-wrong.svelte"</script><Parent childElement={ChildRight} />

So just to clarify, the following should give a type error

Using slot

<script>    import Parent from "./Parent.svelte"    import ChildRight from "./Child-right.svelte"    import ChildWrong from "./Child-wrong.svelte"</script><Parent><ChildWrong /></Parent>

Using svelte:component

<script>    import Parent from "./Parent.svelte"    import ChildRight from "./Child-right.svelte"    import ChildWrong from "./Child-wrong.svelte"</script><Parent childElement={ChildWrong} />

I have come by one solution using svelte:component, where I hardcode the type check. This does not seem like a preferable solution though

<script lang=ts>    import ChildRight from "./Child-right.svelte"    export let childElement;</script><div style="width: 500px; height: 500px; background-color: red;">    {#if childElement === ChildRight}<svelte:component this={childElement} />    {:else}<p>ERROR IN CHILD TYPE</p>    {/if}</div>

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>