My code is correct, but it's becoming difficult to maintain...
interface FuncContainer<F extends (..._: Array<any>) => any> {
func: F
args: Parameters<F>
}
const func: FuncContainer<typeof Math.min> = {
func: Math.min,
args: [3, 4]
}
console.log(func.func(...func.args))
const funcs: Array<FuncContainer<(..._: Array<any>) => any>> = [
{
func: Math.min,
args: [1, 2]
} as FuncContainer<typeof Math.min>,
{
func: fetch,
args: ["https://google.com"]
} as FuncContainer<typeof fetch>
]
console.log(funcs)
Everything compiles without errors. However, the issue arises when dealing with Array<FuncContainer>
. I want to be able to store different functions with varying parameter signatures in a single array, so I opted for a generic function. I also need TypeScript to ensure that the types within each array element are consistent. To achieve this, I used type assertions within each specific array element, but this method is prone to errors since there's no indication if a type assertion is missed for a new element in an Array<FuncContainer>
. Without the required assertion, incorrect argument types won't be detected.
const funcs2: Array<FuncContainer<(..._: Array<any>) => any>> = [
{
func: Math.min,
args: ["5", "6"] // should trigger an error, but it doesn't
}
]
Is there a more efficient way to annotate the array to enforce type checking for the actual type within each position while eliminating the need for manual type assertions like in the provided example? Perhaps utilizing mapped types?
EDIT: I changed unknown
to any
to make it compatible with the playground environment