Skip to content

$state(undefined) is typed as never on svelte-check #14435

Open
@ykrods

Description

@ykrods

Describe the bug

On a project generated by create-vite@5.5.5, running a type check to the following code will get a result that p is typed as never.

<script lang="ts">
  type Person = { name: string }

  let p: Person | undefined = $state(undefined)

  $effect(() => {
    // load person
    setTimeout(() => {
      p = { name: "bob" }
    }, 1000);
  });

  let displayName = $derived(p?.name ?? "anon") // => Error: Property 'name' does not exist on type 'never'. (ts)
</script>
<div>{ displayName }</div>

This is considered a bug because it does not occur when the following changes are made.

-  let p: Person | undefined = $state(undefined) // NG
+  let p: Person | undefined = $state() // OK

Reproduction

https://github.com/ykrods/svelte-reproduction-state-type

Logs

$ npm run check

> svelte-reproduction-state-type@0.0.0 check
> svelte-check --tsconfig ./tsconfig.json && tsc -p tsconfig.node.json


====================================
Loading svelte-check in workspace: /home/ykrods/work/svelte-reproduction-state-type
Getting Svelte diagnostics...

/home/ykrods/work/svelte-reproduction-state-type/src/App.svelte:13:33
Error: Property 'name' does not exist on type 'never'. (ts)

  let displayName = $derived(p?.name ?? "anon")
</script>


====================================
svelte-check found 1 error and 0 warnings in 1 file

System Info

System:
    OS: Linux 6.10 Manjaro Linux
    CPU: (16) x64 AMD Ryzen 7 5700U with Radeon Graphics
    Memory: 8.43 GB / 14.98 GB
    Container: Yes
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.8.0 - /usr/bin/node
    npm: 10.8.3 - /usr/bin/npm
  Browsers:
    Chromium: 131.0.6778.85
  npmPackages:
    svelte: ^5.1.3 => 5.2.8

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions