Home > OS >  TypeScript Array<>.reduce() Types
TypeScript Array<>.reduce() Types

Time:10-05

Is there a way within TypeScript to change the type expected to be returned by an Array.reduce call from the type given to it? The code I'm having an issue with is below for the sake of an example:

let executionSequence: RelationalReversionQuery[][] = this.reduce(
    (accumulator: RelationalReversionQuery|RelationalReversionQuery[][], item: RelationalReversionQuery) => {
    if (accumulator instanceof RelationalReversionQuery) {
        if ((accumulator.ExecutionSequence === RelationalReversionQueryExecutionSequence.Indifferent) && (item.ExecutionSequence === RelationalReversionQueryExecutionSequence.Indifferent)) {
            return [[accumulator, item]]
        }
        return [[accumulator], [item]];
    }
    if (item.ExecutionSequence !== RelationalReversionQueryExecutionSequence.Indifferent) {
        accumulator.push([item]);
        return accumulator;
    }
    if (accumulator.length > 0) {
        let lastArray = accumulator[accumulator.length - 1];
        if (lastArray.length > 0) {
            if (lastArray[lastArray.length - 1].ExecutionSequence === RelationalReversionQueryExecutionSequence.Indifferent) {
                lastArray.push(item);
            } else {
                accumulator.push([item]);
            }
        } else {
            lastArray.push(item);
        }
    } else {
        accumulator.push([item]);
    }
    return accumulator;
});

this is extending the type Array<RelationalReversionQuery>.

CodePudding user response:

This is interesting. The built-in type doesn't allow you to return a different type of the original type unless you specify the 2nd argument of .reduce function in this case.

this.reduce((accumulator: RelationalReversionQuery|RelationalReversionQuery[][], item: RelationalReversionQuery) => {
  // ...
}, []);

//  ^ this is what you need to add
  • Related