Skip to content

Allow $refs to be undefined in Typescript types #11322

Closed
@Etheryte

Description

@Etheryte

What problem does this feature solve?

Currently, when you add $refs annotations to a class-based component, the types are defined as follows:

@Component
export default class Foo extends Vue {
    $refs!: {
        bar: Bar;
    };
}

This is handy and allows you to use refs as expected in class methods:

fooMethod() {
    this.$refs.bar.method();
}

However, the types incorrectly assume that the ref is always present, while it might not be so.

async fooMethod() {
    await longApiRequest();
    this.$refs.bar.method();
}

In the above situation, the ref would be undefined if the component unmounted during the async request.

What does the proposed API look like?

The correct types would ideally mark refs as possibly undefined automatically, or alternatively allow the user to do so.

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

Currently types don't allow this.

The above types would ensure the user correctly checks for the ref before calling a method on it:

async fooMethod() {
    await longApiRequest();
    this.$refs.bar?.method();
    // -----------^
}

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