Patrickkx
Patrickkx

Reputation: 1870

Function that takes generic arguments and returns generic value

I have a function:

const r = (array, function) => { some stuff }

However array and function arguments can be anything, but array must be typeof array and function must be typeof function.

However, the array can be array of anything - any[] anf function can be anything function(...r: any): any.

How can I type that r function to accept generic array and function arguments, but the type definition has to be passed when calling it?

E.g. Im calling it somewhere in my app:

r([1,2,3], (r) => r + 2)

Thanks!

Upvotes: 0

Views: 56

Answers (2)

Karol Majewski
Karol Majewski

Reputation: 25850

Try this:

const r = <T>(array: T[], fn: (argument: T) => T) => { /* ... */}

Upvotes: 0

Erik van Velzen
Erik van Velzen

Reputation: 7062

This is my interpretation of what your're looking for

type Fn<T> = (arg: T) => T
type R = <T>(array: T[], fn: Fn<T>) => T

const r: R = (array, fn) => { 
    //some stuff
}

I prefer to split the type declaration and its usage.

Upvotes: 1

Related Questions