Trying to create a versatile function type for data transformation can be a bit tricky. When dealing with a single object, it's straightforward:
export type SingleObjFunction<InputDataType, OutputDataType> =
(object: InputDataType) => OutputDataType;
However, when working with an array of objects, I want the function to return either an object with a field: OutputDataType[]
property inside, or just a plain array. Is it possible to achieve this flexibility by using another generic parameter like so:
export type MultipleObjFunction<
InputDataType,
OutputDataType,
InnerField extends (string | undefined),
FunctionResult = InnerField extends string
? { [Key in InnerField]: OutputDataType[] }
: OutputDataType[]
> = (objs: InputDataType[]) => FunctionResult
I am aware that there is no direct equivalent to valueof
, but perhaps there is an alternative approach?