Skip to content

Allow $refs to be undefined in Typescript types #415

Closed
@Etheryte

Description

@Etheryte

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.

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