Skip to content

$props tagged union across multiple props does not type narrow #14781

@cloudymeatball

Description

@cloudymeatball

Describe the bug

Tagged union props does not type narrow in switch or if.

I am not sure if it was ever supported in svelte 5. Problem appears to go away if instead combining type, properties using a single prop wrapper: {type, properties} then wrapper.type, wrapper.properties etc. So there was not really an equivalent in svelte 4 export let syntax for comparison. I wrote the tagged union types a while ago but only now making use of the inferences or narrowing.

Reproduction

<script lang=ts>
  let {type, properties} : ({
    type: 'student'
    properties: { studentId: number }
  } | {
    type: 'teacher'
    properties: { teacherId: number }
  }) = $props()

  switch (type){
    case 'student':
      console.log(properties?.studentId)
  }

  if (type === 'student'){
    console.log(properties?.studentId)
  }
</script>

// error: Property 'studentId' does not exist on type '{ studentId: number; } | { teacherId: number; }'.

Expected behavior: ts playground

Logs

No response

System Info

svelte^5.0.0
typescript^5.0.0
vite-plugin-svelte^5.0.0

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions