Below is a snippet of code that showcases different types of functions and a function aggregator:
// Function that accepts any type of argument
const function1 = (parameter: any) => parameter;
// Function that requires a number to work
const function2 = (parameter: number) => parameter + 5;
// Function that requires a string to work
const function3 = (parameter: string) => parameter.split(':');
// Combinatorial function that combines two functions into a "meta function"
function functionAggregator<A1, R1, R2>(f1: (a1: A1) => R1, f2: (a1: A1) => R2): (a1: A1) => [R1, R2] {
return (a1: A1) => [f1(a1), f2(a1)];
}
const validMetaFunction = functionAggregator(function1, function2);
// Valid because parameters of type number and any can overlap
const invalidMetaFunction = functionAggregator(function2, function3);
// Invalid because parameters of type number and string cannot overlap
const validFunctionResult = validMetaFunction(5);
// Valid result, since we passed in a number
const invalidFunctionResult = validMetaFunction('string');
// This line should ideally throw an error as the function expects a number, not a string
In the last line, validMetaFunction('string');
should ideally be marked as invalid code. However, due to the widened type of any
in function1
, the metaFunction's parameter type becomes any
. Is there a way to resolve this issue?