Home > front end >  Extract parameters of function using generics
Extract parameters of function using generics

Time:01-26

What is the correct way of extracting parameters of a function using generics?

I'm trying to extract the parameters of this function:

interface Props<T> {
    data: T[];
    test: (x: T) => void
}

function fn<T>(props: Props<T>): void {
    return;
};

And pass them to a new function fn2. So that I would be the equivalent tofn. Using the following does not work

type GetProps<T extends any> = T extends (props: infer U) => void ? U: never
type FnProps = GetProps<typeof fn>

function fn2<T>(props: FnProps<T>): void { // Type 'FnProps' is not generic
    return;
}

What is the correct way of writing GetProps here?

Playground

CodePudding user response:

If I got your question correctly you could write your utility type as

type FnProps<T> = GetProps<typeof fn<T>>

and then

function fn2<T>(props: FnProps<T>): void {
    return;
}
  • Related