I'm new to generics in typescript, it's confusing
is there a way to make the spread operator ... work in the snippet below
the issue
the line [ key: U, ...rest: Reg[U] ], doesn't work as I expect
the question
what am I doing wrong ?
I tried to make this work but couldn't
possible solutions i didnt try yet
function overloading
type Registery = {
"item.1": [name: string]
"item.2": [id: number, ready: "Y" | "N"]
"item.3": [ok: boolean]
}
type ReK = keyof Registery
const send = <
T extends ReK | ReK[] | "*" | never = never
>(
key: T,
callback: (
...args:
T extends Array<infer U>
? (
U extends ReK
? [ key: U, ...rest: Registery[U] ]
: never
)
: T extends string
? (
T extends ReK
? Registery[T]
: T extends "*"
? Registery[ReK]
: never
)
: never
) => any
) => { /** */ }
send("item.2", (...args) => {
const [
arg1,
//^?const arg1: number
arg2,
//^?const arg2: "Y" | "N"
] = args
})
send(["item.1", "item.2"], (key, ...args) => {
// ^?
const k = key
// ^?const k: "item.1" | "item.2"
if (key == "item.1") {
const [
arg1,
//^?const arg1: string | number
arg2,
//^?const arg1: string | number
] = args
}
if (key == "item.2") {
const [
arg1,
//^?const arg1: string | number
arg2,
//^?const arg2: string | number
] = args
}
})
here's a link to ts playground https://tsplay.dev/mxEQ7W
Registerywith that secondeis distracting).T | T[] | "*"or "[key: U, ...rest: Reg[U]]"`. Instead it's the lack of microsoft/TypeScript#46680 that's the problem. If you give up on destructuring the union of tuples like this playground link shows then it works. It's ugly, but it works. Does that fully address the question? If so I'll write up an answer explaining; if not, what am I missing?