Consider the following scenario:
const elements = [
{ fieldA: true },
{ fieldB: true },
{ fieldA: true, fieldB: true },
{ fieldB: true },
{ fieldB: true },
];
const [withFieldA, withoutFieldA] = elements.reduce(
(acc, entry) => {
const { fieldA } = entry;
const hasField = Boolean(fieldA);
return acc[+!hasField].push(entry) && acc;
},
[[], []],
);
console.log('withFieldA', withFieldA);
console.log('withoutFieldA', withoutFieldA);
This code is functional, but TypeScript errors are being encountered.
An attempt was made to,
type TElement = {
fieldA?: boolean;
fieldB?: boolean;
}
const elements = [
{ fieldA: true },
{ fieldB: true },
{ fieldA: true, fieldB: true },
{ fieldB: true },
{ fieldB: true },
] as TElement[]
const [withFieldA, withoutFieldA]: [TElement[], TElement[]] = elements.reduce(
. . . . .
However, that solution did not work.
What would be the correct way to type this?