#Inferring generic type parameters
1 messages · Page 1 of 1 (latest)
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
...```
You can choose specific lines to embed by selecting them before copying the link.
Here's one solution:
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
...```
You can choose specific lines to embed by selecting them before copying the link.
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/ReturnTypeif you can. In this case you generic over rest of the arguments rather than generic over the entireupdater. - Not what you are asking, but I cleaned up your
listUpdaterfunction. You can generic over the element rather than generic over the array.
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