maheryhaja
maheryhaja

Reputation: 1687

Enforce same length for array of parameters and function parameters

I want to implement an NgRx SignalStore feature, the syntax would be like:

withDetailFetching({ 
   contact: {
       argsFromRouterParams: ['contactId', 'tenantId'],
       method: (contactId: string, tenantId: string) => { }
   },
   userId: {
       argsFromRouterParams: ['userId'],
       method: (userId: string) => { }
   }
})

In this code, I want to enforce the typing so the number of parameters sent to contact.method (for example) is the same as the length of contact.argsFromRouterParams.

The typing I've already tried is below:

class WithDetailFetchingParam<T extends string[]> {
    argsFromRouterParams: T;
    method: () => (...args: NoInfer<T>) => any;
}

export function withDetailFetching<const P extends string[] >(param: { [key: string]: WithDetailFetchingParam<P>} ) {
// implementation
}

This typing works but it does not allow me to have different length for arrays contact.argsFromRouterParams and user.argsFromRouterParams:

Working:

withDetailFetching({ 
   contact: {
       argsFromRouterParams: ['contactId', 'tenantId'],
       method: (contactId: string, tenantId: string) => { }
   }
})

Not working:

withDetailFetching({ 
   contact: {
       argsFromRouterParams: ['contactId', 'tenantId'],
       method: (contactId: string, tenantId: string) => { }
   },
   userId: {
       argsFromRouterParams: ['userId'],
       method: (userId: string) => { }
   }
})

I've already found Enforce number of parameters of a function depending length of a given array, which helped me to do the typing above, but my need is little bit different.

How can I modify this implementation to allow for varying lengths of argsFromRouterParams while maintaining type safety between the parameters and the method?

Upvotes: 1

Views: 50

Answers (0)

Related Questions