Skip to content

Needer a helper to extract components type interface when importing a ref #1341

Closed
@BlakeTheAwesome

Description

@BlakeTheAwesome

What problem does this feature solve?

I have a component (lets call it MyForm) that is bound in a template using <my-form ref="formRef />.
My setup function wants to look something like:

setup() {
  const formRef = ref<MyForm>();
  function onClick() { formRef.value.clear(); }
  return { formRef, onClick}
}

The issue is that I can't get good type information for MyForm and its clear function, because the import is the return type of defineComponent(), which doesn't appear to contain the fields exported from its setup function.

This means there I have no type safety when using a component as a ref.

My current workaround is to move the setup function out of defineComponent(), and then have export type MyFormType = ReturnType<typeof setup> and import it separately.

This will only work for components I can change the source on though.

It would be good if there be a simple way to extract the interface from an import so that you could do something like:

type FormType = VueExtractType<typeof MyForm>;
const formRef = ref<FormType>();

It would be even better if ref() had a type overload for components that returned something conforming to that types interface.

There might already be something that does this, but I was unable to locate it by reading through the runtime-core.d.ts file.

What does the proposed API look like?

const myComponent = defineComponent({
  setup() { 
    return { clear: () => {}; }
});
type componentType = ComponentType<typeof myComponent>;
const myRef = ref<componentType>();
const myRef = ref<typeof myComponent>(); // Ideally this would also work 

myRef.value.clear(); // now has type information for clear()

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