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

Provide/extract component prop typing in libraries #1619

Closed
Schlechtwetterfront opened this issue Jul 18, 2020 · 1 comment
Closed

Provide/extract component prop typing in libraries #1619

Schlechtwetterfront opened this issue Jul 18, 2020 · 1 comment

Comments

@Schlechtwetterfront
Copy link

What problem does this feature solve?

I'm writing a small library for Vue 3 which contains a function

function fn(component, props) {}

which takes a component definition (component options) as first argument and the component's props as second argument. These props will be passed to an actual instance of the component later.

Given a component definition, I want to provide the actual type of the props to the user. Idea:

function fn<TComponent>(component: TComponent, props?: ExtractProps<TComponent>) {}

So if I had a component like this:

const SomeComponent = defineComponent({
  props: {
    prop1: {
      type: String,
      default: 'defaultVal',
    },
});

My call to fn would then type the second parameter as { prop1: string }

import SomeComponent from '...';

// Type checking ok
fn(SomeComponent, { prop1: 'test' })

// This would fail
fn(SomeComponent, { prop2 : 1 })

I had something similar working for a beta of Vue 3 here, but this no longer works (as of rc 1). I wanted to rebuild this with rc 1, but it seems I can't, because one of the returned types of defineComponent (ComponentPublicInstanceConstructor) is not exported and thus I can't use it in my conditional type.

So:

  1. Is this currently possible and I just missed how?
  2. Is this approach even idiomatic or is there an alternative "best practice" approach for this?

Thanks.

What does the proposed API look like?

Not sure, maybe exporting ComponentPublicInstanceConstructor is sufficient?

@yyx990803
Copy link
Member

yyx990803 commented Jul 19, 2020

If the type you got is a return type from defineComponent, it is a constructor so you should be able to get its props type as InstanceType<TComponent>['$props']. This is also what TSX uses to infer props.

@github-actions github-actions bot locked and limited conversation to collaborators Nov 9, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants