Hi everyone, I'm trying to define types for a function I have defined a couple of months ago in javascript. The function itself accepts a series of arguments whose rule generally goes by:
- no. arguments must be even
- for every args[i] where i % 2 == 0 with type T there must be an args[i+1] having type (x: T) => any
This is what I've came up in a couple of hours. Even tho it makes sense to me logically, typescript does not seem to want it. The compiler complains: "Expected 0 arguments, but got 2.ts(2554)", seemingly not matching any type at all
type FunctionTaking<T> = (x: T) => unknown
type ValidPatternType = Record<string, any> | Record<string, never> | Array<unknown> | null | number | string
type FlattenPairs<T> = T extends [infer U, infer F, ...infer Rest]
? U extends ValidPatternType
? F extends FunctionTaking<U>
? Rest extends Array<unknown>
? [U, F, ...FlattenPairs<Rest>]
: [U, F]
: []
: []
: []
function matchArgs<T extends Array<unknown>>(...args: FlattenPairs<T>): void {
console.log(args)
}
matchArgs(5, (test: number) => test) // Error: Expected 0 arguments, but got 2.ts(2554)