Suppose we have following code:
// a value, and a function that will be called with this value
type ValueAndHandler<T> = [value: T, handler: (value: T) => void]
type Params = {
// not sure how to type it
valuesAndHandlers: ValueAndHandler<???>[]
// it's not the only field in the structure
// so I cannot just pass array as variadic arguments
otherStuff: number
}
function doSomethingWithParams(params: Params){/* something, not important*/}
doSomethingWithParams({
// array of some pairs of handlers and values
// each value is only related to its handler, and not to other handlers/values
valuesAndHandlers: [
[5, value => console.log(value.toFixed(3))],
["example", value => console.log(value.length)]
],
otherStuff: 42
})
In this code I want the type of parameter of first handler to be inferred as number
, and type of parameter of second handler to be inferred as string
; but that's not happening (because I typed them as unknown
in variable definition).
How can I type the definition so proper type for each handler is inferred individually?
I tried to add a default type for generic parameter, but it's not helping, because it's still the same for all the pairs.
I also tried to use satisfies
without explicitly typing the variable, but that worked just the same.
I have also seen this question, but could not apply that technique to my case.