Typescript reduce an array of number literal type

Typescript reduce an array of number literal type

When working with TypeScript, you may come across a situation where you need to reduce an array of number literal types. In this blog post, we will explore how to achieve this and provide multiple solutions to the problem.

Solution 1: Using a type assertion

One way to reduce an array of number literal types is by using a type assertion. This involves asserting the array to a union of the literal types and then reducing it.

const numbers: [1, 2, 3, 4, 5] = [1, 2, 3, 4, 5];

const sum = numbers.reduce((acc, curr) => acc + curr as 1 | 2 | 3 | 4 | 5, 0);

console.log(sum); // Output: 15

In this solution, we assert the acc and curr parameters to the union of the literal types using the as keyword. This ensures that the types are compatible and allows us to perform the reduction operation.

Solution 2: Using a type guard

Another approach is to use a type guard to narrow down the type of the array elements during the reduction process.

const numbers: [1, 2, 3, 4, 5] = [1, 2, 3, 4, 5];

function isNumber(value: number): value is 1 | 2 | 3 | 4 | 5 {
  return [1, 2, 3, 4, 5].includes(value);
}

const sum = numbers.reduce((acc, curr) => {
  if (isNumber(curr)) {
    return acc + curr;
  }
  return acc;
}, 0);

console.log(sum); // Output: 15

In this solution, we define a type guard isNumber that checks if the value is one of the literal types in the array. The type guard narrows down the type of curr within the reduce callback, allowing us to perform the addition operation.

Solution 3: Using a custom reducer function

If you prefer a more reusable approach, you can create a custom reducer function that accepts an array of number literal types and reduces it.

type NumberLiteral = 1 | 2 | 3 | 4 | 5;

function numberLiteralReducer(numbers: NumberLiteral[], initialValue: NumberLiteral): NumberLiteral {
  return numbers.reduce((acc, curr) => acc + curr, initialValue);
}

const numbers: NumberLiteral[] = [1, 2, 3, 4, 5];

const sum = numberLiteralReducer(numbers, 0);

console.log(sum); // Output: 15

In this solution, we define a custom numberLiteralReducer function that accepts an array of number literal types and an initial value. This function internally uses the reduce method to perform the addition operation and returns the final sum.

These are three different solutions to reduce an array of number literal types in TypeScript. Choose the one that best fits your requirements and enjoy working with TypeScript!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *