Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incomplete type narrowing in event handlers #1750

Closed
abaumg opened this issue Aug 22, 2022 · 3 comments
Closed

Incomplete type narrowing in event handlers #1750

abaumg opened this issue Aug 22, 2022 · 3 comments
Labels
question Further information is requested

Comments

@abaumg
Copy link

abaumg commented Aug 22, 2022

It seems that vue-tsc cannot narrow types in event handlers, e.g. when checking for null.

In the following demo code, Volar infers the the correct type (User) in the template expression (mustache tag), but not in the click handler.

  <div v-if="user !== null">
    <h1 @click="doSomething(user.email)">
      user's emailAddress: {{ user.email }}
    </h1>
  </div>
</template>

<script setup lang="ts">
type User = {
  id: number;
  email: string;
}

let user: null | User;

function doSomething(email: any) {
  console.log(email);
}
</script>

vue-tsc incorrectly complains about Object is possibly 'null'. ts(2531) in line 3 (@click="..."), ignoring the null check (user !== null) in the line above.

@austin-agronick
Copy link

The issue also effects v-if/else logic as well. For example this code will result in vue-tsc errors: let user2: string | User and <span v-if="user2.id">({{ user2.id }})</span>. "Property 'id' does not exist on type 'string | User'"

For a live example see: https://stackblitz.com/edit/vue3-typescript-vue-cli-starter-zkvkhm?file=src/components/HelloWorld.vue

@johnsoncodehk
Copy link
Member

Use vueCompilerOptions.experimentalAllowTypeNarrowingInInlineHandlers.

{
  "vueCompilerOptions": {
    "experimentalAllowTypeNarrowingInInlineHandlers": true
  }
}

@johnsoncodehk johnsoncodehk added the question Further information is requested label Aug 27, 2022
@abaumg
Copy link
Author

abaumg commented Aug 29, 2022

For the sake of completeness: This seems to be resolved in #1249

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants