As a newcomer to generics in typescript, I find it quite perplexing
Is there any way to get the spread operator ...
to function correctly in the code snippet below?
The Dilemma
The line [ key: U, ...rest: Reg[U] ]
is not behaving as I anticipated
The Query
What am I missing here?
I attempted to resolve this issue but hit a roadblock
Potential Solutions I Haven't Explored Yet
Function Overloading
type Registrar = {
"item.1": [name: string]
"item.2": [id: number, ready: "Y" | "N"]
"item.3": [ok: boolean]
}
type ReKey = keyof Registrar
const transmit = <
T extends ReKey | ReKey[] | "*" | never = never
>(
key: T,
callback: (
...args:
T extends Array<infer U>
? (
U extends ReKey
? [ key: U, ...rest: Registrar[U] ]
: never
)
: T extends string
? (
T extends ReKey
? Registrar[T]
: T extends "*"
? Registrar[ReKey]
: never
)
: never
) => any
) => { /** */ }
transmit("item.2", (...args) => {
const [
arg1,
//^?const arg1: number
arg2,
//^?const arg2: "Y" | "N"
] = args
})
transmit(["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
}
})
Check out the TypeScript playground for more details: https://tsplay.dev/mxEQ7W