Let's consider the following simplified example that showcases my issue:
const customFactory = <T extends unknown[]>(
customFn: (...args: T) => void
) => {
const modifiedCustomFn = (...args: T) => {
console.log('Called with arguments:', ...args)
return customFn(...args)
}
// initialization
modifiedCustomFn() // TypeScript error occurs here
return modifiedCustomFn
}
// implementation:
const customFunction = (numberValue?: number, stringValue?: string) => {
return JSON.stringify({ numberValue, stringValue })
}
customFactory(customFunction)()
Upon execution, I encounter a TypeScript error message:
The argument type '[]' cannot be assigned to the parameter type 'T'. While '[]' fits within the constraint of type 'T', it's plausible for 'T' to potentially instantiate a distinct subtype other than 'unknown[]'.
If I were to provide this function instead:
const customFunction = <T extends unknown[]>(...args: T) => {
return args
}
customFunction()
This is perplexing. How do I go about persuading TypeScript that both cases refer to the same T
?