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

Its possible define component with generic type? #2733

Closed
martinsura opened this issue Dec 5, 2020 · 3 comments
Closed

Its possible define component with generic type? #2733

martinsura opened this issue Dec 5, 2020 · 3 comments

Comments

@martinsura
Copy link

What problem does this feature solve?

Hello, first -> thanks for the Vue3. Its Awesome.

In my previous project I often use typescript generic. For example:

const CustomButton = defineComponent({
  props: {
    clickRequest:Function as PropType<(r?: Promise<any>) => void>,
    onClick: Function as PropType<(data:any) => void>
  },
  emits:["click"],
  setup(props, { emit }) {
    const internalClick = async () => {
      const data = await props.clickRequest()
      emit("click",data);
    }
    return () => {
      <button onClick={internalClick}>Action</button>
    }
  }
})

This example works as expected. Problem is any type around props definition.

What does the proposed API look like?

const CustomButton = defineComponent<T>({
  props: {
    clickRequest:Function as PropType<(r?: Promise<T>) => void>,
    onClick: Function as PropType<(data:T) => void>
  },
  emits:["click"],
  setup(props, { emit }) {
    const internalClick = async () => {
      const data = await props.clickRequest()
      emit("click",data as T);
    }
    return () => {
      <button onClick={internalClick}>Action</button>
    }
  }
})

Thanks

@Zcating
Copy link
Contributor

Zcating commented Dec 7, 2020

As work around, You can do this to provide a generic type.

const GenericComponent = <T>() => defineComponent({
  // add your defination.
});

Also you can declare a class component


export declare class GenericComponent<T> {
  // add your defination
}

@posva
Copy link
Member

posva commented Dec 7, 2020

Since you could define a component with as many generics as you want, you will have to use a function like proposed above:

function defineGenericComponent<T, D>() {
  return defineComponent({ ... })
}

Remember to use the forum or the Discord chat to ask questions!

@posva posva closed this as completed Dec 7, 2020
@pikax
Copy link
Member

pikax commented May 3, 2021

For future reference RFC to allow this

@github-actions github-actions bot locked and limited conversation to collaborators Oct 21, 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

4 participants