Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Infer type of callback argument into one of the returned function

I have composable function like this:

export function useAppModal(beforeOpen?: <???>) => void) {
  const modal = ref()
  // calling open with any arguments will be passed to beforeOpen callback
  const open = (...args: <???>) => {
    beforeOpen?.(...args)
    modal.value?.open()
  }
  const close = () => {
    modal.value?.close()
  }
  return { modal, open, close }
}

I want to infer the type of beforeOpen into function open.

So that when I call useAppModal like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const { modal, open, close } = useAppModal((arg1: number, arg2: string[]) => {
    // do something
})

open() // should error:

    Expected 2 arguments, but got 0.
    An argument for 'arg1' was not provided.
    const open: (arg1: number, arg2: string[]) => void

And beforeOpen is optional, so when call useAppModal without any arguments, I want the type of open to be () => void

>Solution :

you can use T extends unknown[].

TS Playground

function useAppModal<T extends unknown[]>(beforeOpen?: (...args: T) => void) {
  // calling open with any arguments will be passed to beforeOpen callback
  const open = (...args: T) => {
    beforeOpen?.(...args)
  }
  const close = () => {
    //
  }
  return { open, close }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading