2

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>.

2
  • What exactly is the issue? What do you expect happens and what happens instead? Commented Oct 5, 2021 at 5:30
  • @VLAZ Code-wise it works without the type issues in JavaScript, but in TypeScript I'm getting type errors in WebStorm. I'm expecting to take in an Array<RelationalReversionQuery> and output an Array<Array<RelationalReversionQuery>> - that is, there's a type change which occurs within the accumulator. Commented Oct 5, 2021 at 5:43

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.