I'm currently working on a task to develop a versatile function that accepts a parameter called hashMapName, another parameter called 'keys' which can be either a string or an array of strings, and a callback function that will return either a single value of type T or an array of values of type T.
The function should return T if the key is a string and T[] if the key is a string[].
Here is the code I have attempted:
export function getData<K extends string | string[], T>(
hashMapName: string,
keys: K extends string[] ? string[] : string,
serviceCallBack: K extends string[] ? () => Promise<T[]> : () => Promise<T>
): Promise<T> {
return Array.isArray(keys)
? getDataForKeys<T>(hashMapName, keys, serviceCallBack)
: getDataForKey<T>(hashMapName, keys, serviceCallBack);
}
However, I'm encountering a TypeScript error regarding the 'keys' parameter in the getDataForKey function.
Error:
Argument of type 'K extends string[] ? string[] : string' is not assignable to parameter of type 'string'.
Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.
Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.
Update 1:
Below are the declarations for the getDataForKeys and getDataForKey functions.
declare function getDataForKey<T>(
hashMapName: string,
key: string,
serviceCallBack: () => Promise<T>
)
declare function getDataForKeys<T>(
hashMapName: string,
key: string[],
serviceCallBack: () => Promise<T[]>
)
Since we strictly adhere to the noExplicitAny policy, we are unable to utilize the 'any' keyword for the functional parameters.
Following the suggestion provided by @Dmitriy, I am now facing the following issue.
Argument of type '(() => Promise<T[]>) | (() => Promise<T>)' is not assignable to parameter of type '() => Promise<T[]>'.
Type '() => Promise<T>' is not assignable to type '() => Promise<T[]>'.
Type 'Promise<T>' is not assignable to type 'Promise<T[]>'.
Type 'T' is not assignable to type 'T[]'