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

Allow $refs to be undefined in Typescript types #415

Closed
Etheryte opened this issue Apr 18, 2020 · 1 comment
Closed

Allow $refs to be undefined in Typescript types #415

Etheryte opened this issue Apr 18, 2020 · 1 comment

Comments

@Etheryte
Copy link

Currently, $refs annotations on a class-based component don't allow you to mark them as possibly undefined:

@Component
export default class FooComponent extends Vue {
  $refs!: {
    bar: BarComponent | undefined;
  }
}

The above doesn't compile:

Property 'bar' is incompatible with index signature.
Type 'BarComponent | undefined' is not assignable to type 'Vue | Element | Vue[] | Element[]'.

Setting a ref as possibly undefined should be allowed to correctly type cases handling async logic. In the below case the ref would be undefined if the component unmounted during the async operation:

@Component
export default class FooComponent extends Vue {
  $refs!: {
    bar: BarComponent;
  }

  async mounted() {
    await this.longApiCall();
    this.$refs.bar.doSomething();
  }

  private longApiCall() {
    return new Promise(resolve => setTimeout(resolve, 1000));
  }
}

Marking the ref as BarComponent | undefined would enforce checking the ref before using it:

async mounted() {
  await this.longApiCall();
  this.$refs.bar?.doSomething();
}

Currently, however, the types don't allow this.

@Etheryte
Copy link
Author

This will be fixed once vuejs/vue#11112 gets merged.

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

No branches or pull requests

1 participant