Open hyunbinseo opened 2 months ago
If you want to use it in a derived it has to be state
<script lang="ts">
let b: HTMLParagraphElement = $state();
const b2 = $derived(b?.children);
$inspect(b2);
</script>
<p bind:this={b}></p>
this works fine (and the error that you are seeing on b is just about the intersection between HTMLParagraphElement
and undefined
being never. So i would cheat a bit and use only HTMLParagraphElement
while still using the nullish to avoid the derived throwing (it also depends on where you are using the derived...if you don't access it immediately you can also avoid the nullish.
My bad and thank you. Maybe this should be a documentation issue?
// HTMLElement | undefined
let article = $state<HTMLElement>();
// HTMLCollection | undefined
const children = $derived(article?.children);
My bad and thank you. Maybe this should be a documentation issue?
// HTMLElement | undefined let article = $state<HTMLElement>(); // HTMLCollection | undefined const children = $derived(article?.children);
What's exactly the documentation issue?
Providing an example of bind:this
and $state()
in the docs will be helpful.
Since the following is valid in Svelte 5 runes, I honestly didn't thought using $state()
was viable.
<script lang="ts">
let div: HTMLDivElement;
</script>
<div bind:this={div}></div>
Going one step further, maybe forcing $state
with bind:this
in Svelte 6 could be an option?
In the example code, canvasElement
is initially undefined
, but is typed as HTMLCanvasElement
.
<script>
import { onMount } from 'svelte';
/** @type {HTMLCanvasElement} */
let canvasElement;
onMount(() => {
const ctx = canvasElement.getContext('2d');
drawStuff(ctx);
});
</script>
<canvas bind:this={canvasElement} />
Forcing $state
will fix this problem:
<script lang="ts">
// HTMLDivElement | undefined
let div = $state<HTMLDivElement>();
</script>
<div bind:this={div}></div>
As i've said technically you don't really need $state
if the div never changes...you only need it in your case because you are reading the derived immediately. For example
<script lang="ts">
let a;
const a2 = $derived(a.children);
</script>
<button onclick={()=>{
console.log(a2);
}}>
log child
</button>
<p bind:this={a}></p>
this doesn't cause any problems because you are accessing a2
when a
was already set.
However i agree that we need specific documentation around this topic so i'll keep this open with the doc label
Describe the bug
Reproduction
See above.
Logs
No response
System Info
Severity
annoyance