#Infer value specific to each element in tuple

12 messages · Page 1 of 1 (latest)

lusty moonBOT
#
._.ewok#0

Preview:```ts
function test<P extends number>(
...array: [P, (param: P) => any][]
) {
array.forEach(([p, fn]) => fn(p))
}

test(
[
1,
param => {
// let ts know param = 1
},
],
[
2,
param => {
// let ts know param = 2
},
]
)```

chrome canyon
#

Infer value specific to each element in tuple

royal quest
#

I don't think it is possible, because P is shared between all members

#

There isn't really a way to say that P can be anything, but PN1 must much PN2

#

You probably need something like

test([
  item(1, param => {}),
  item(2, param => {}),
])
chrome canyon
hot widget
#

@chrome canyon This is possible, you need to be generic on an entire tuple of input and map over it:

lusty moonBOT
#
function test<T extends number[]>(...array: { [K in keyof T]: [T[K], (param: T[K]) => void] }) {
    array.forEach(([p, fn]) => fn(p));
}

test([1, param => {
//       ^? - (parameter) param: 1
}], [2, param => {
//      ^? - (parameter) param: 2
}]);
hot widget
#

(I knew I had seen this somewhere - managed to find a previous answer from @wide compass)

royal quest
#

😲

#

Cool trick