#Inferring generic type parameters

1 messages · Page 1 of 1 (latest)

alpine moat
#

Hi, I'm struggling a bit with higher order functions - I'm wondering how I can fix the following code so that the myListUpdater function infers the types of the parameters correctly.

shadow gyroBOT
#
googlefeud#0

Preview:```ts
type ValueUpdater<T> = (
previous: T,
...args: any[]
) => T
type Tail<T extends any[]> = T extends [
infer A,
...infer R
]
? R
: never

function listUpdater<T extends any[]>(
list: T,
action: "add" | "remove",
value: T[number]
) {
// Implementation
return list
...```

lunar aurora
#

Here's one solution:

shadow gyroBOT
#
nonspicyburrito#0

Preview:```ts
function listUpdater<T>(
list: T[],
action: "add" | "remove",
value: T
) {
// Implementation
return list
}

listUpdater([1, 2, 3], "remove", 2) // Works fine

function createUpdater<
T,
K extends keyof T,
A extends unknown[]

(
stateFn: (up
...```

lunar aurora
#

Some notes:

  • Not sure if there's a way to make it so that you don't have to write listUpdater<number> to specialize.
  • In general, you want to write in a way that avoids things like Parameters/ReturnType if you can. In this case you generic over rest of the arguments rather than generic over the entire updater.
  • Not what you are asking, but I cleaned up your listUpdater function. You can generic over the element rather than generic over the array.
alpine moat
#

Thanks, just what I needed. It's fine for the generic parameter to stay cuz the list updater fn is the only one with generics