Skip to content

vue-tsc doesn't properly narrow discriminated unions in template #4629

@MikeBellika

Description

@MikeBellika

Vue - Official extension or vue-tsc version

vue-tsc version: 2.0.29

VSCode version

N/A - Using vue-tsc from cli

Vue version

3.4.34

TypeScript version

5.4.5

System Info

System:
    OS: macOS 14.5
    CPU: (8) arm64 Apple M3
    Memory: 143.56 MB / 8.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.1.0 - ~/.nvm/versions/node/v22.1.0/bin/node
    npm: 10.7.0 - ~/.nvm/versions/node/v22.1.0/bin/npm
    pnpm: 9.4.0 - ~/.nvm/versions/node/v22.1.0/bin/pnpm
  Browsers:
    Chrome: 127.0.6533.88
    Safari: 17.5

Steps to reproduce

  1. Clone https://github.com/MikeBellika/union-type-repro
  2. Run pnpm type-check

What is expected?

In ReproComponent.vue, there should be no errors. The type is defined to be either
{ text: string; subheading: { text: string } } or
{ text?: undefined; subheading?: undefined }.
So if text is defined, subheading will definitely be defined.
On line 17 we check if truthy and only then do we use the value from subheading. According to the types, subheading cannot be undefined, because we already checked text.

This error only occurs in the template, not in the script tag. You can see on line 11 we do the same thing but this time with no error.

Furthermore, when using the component we don't get an error when defining text, without defining subheading. You can see this in App.vue.

What is actually happening?

There's an error on line 21, where we use subheading:

src/components/ReproComponent.vue:21:8 - error TS18048: '__VLS_ctx.subheading' is possibly 'undefined'.

21     {{ subheading.text }}
          ~~~~~~~~~~


Found 1 error.

Link to minimal reproduction

https://github.com/MikeBellika/union-type-repro

Any additional comments?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions