Closed
Description
Describe the bug
Given a $state that can be an object or undefined and a function that mutates the object and the state at the same time
<script lang="ts">
let data = $state<{ num: number } | undefined>({ num: 1 });
function expire() {
data.num = data.num - 1;
if (data.num <= 0) data = undefined;
}
</script>
{#if data}
<button {expire}>Click</button>
<p>expires in {data.num} click</p>
{/if}
If you try to access an object property in the template you get an error in the console about reading property of null.
You can work around the problem using optional chaining data?.num
but considering the property is accessed inside an if block I would expect to not need it
Reproduction
Logs
Error: Cannot read properties of undefined (reading 'num')
System Info
svelte 5.0.0-next.26
Severity
annoyance
Metadata
Metadata
Assignees
Labels
No labels