Here is an array I have:
const myArray: (
| { feature1: true; feature2: [number, number] }
| { feature1: false; feature2: [number, number, number] }
)[] = [
{ feature1: true, feature2: [1, 2] },
{ feature1: false, feature2: [3, 4, 5] },
];
I want to multiply all the numbers in this array by two. This is what I am trying to do:
// Please don't scrutinize this function, it's accurate
export const modifyElements = <T extends unknown[], R>(
array: T,
callback: (value: T[number], index: number, array: T) => R,
): { [K in keyof T]: R } =>
array.map(
callback as (value: unknown, index: number, array: unknown[]) => R,
) as { [K in keyof T]: R };
const modifiedResult: typeof myArray = myArray.map(({ feature1, feature2 }) => ({
feature1,
feature2: modifyElements(feature2, (x) => x * 2),
}));
However, it shows an error
Type 'boolean' is not assignable to type 'false'
.
To solve this issue, I am currently using a somewhat ridiculous ternary operator:
const modifiedResult: typeof myArray = myArray.map(({ feature1, feature2 }) =>
feature1
? { feature1, feature2: modifyElements(feature2, (x) => x * 2) }
: { feature1, feature2: modifyElements(feature2, (x) => x * 2) },
);
Is there a more elegant solution for this problem?