Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

934
Visualizações
Typescript union type array `a[] | b[]` is not `reduce`able, but `map`able

I'm trying to reduce over a union of array-types: foo[] | bar[]. With map it works as expected and I get an element of foo|bar in the lamda, but it does not work with reduce. I get the error, that 'the expression is not callable, because the signatures are not compatible'.

Maybe this is related, but that was in TS 3.6 days, and I'm using 4.5. Is there a (neat) way around this?

I have a Typescript Playground here

const m = [] as Array<number | string>;
m.reduce((it) => it); // ok
m.map((it) => it); // ok

const m2 = [] as Array<number> | Array<string>;
m2.reduce((it) => it);
m2.reduce((it) => it as any);  // not even with 'any'-lambda
// This expression is not callable.
// Each member of the union type '<OMITTED> ...' has signatures, but none of those signatures are compatible with each other.
m2.map((it) => it); // why does `map` work then ?

// same with tuples
const m3 = [1, 1] as [number, number] | [string];
m3.map((it) => it);
m3.reduce((it) => it); // same error
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In addition to jcalz comment I found the following.

Typescript Definitions

The function signature for map is

export function map<T, U>(iterable: Iterable<T>, mapper: (value: T, index: number, iterable: Iterable<T>) => U): U[];

It has a different return type U then it's input T.

One of the function signatures for reduce is

export function reduce<T>(
   iterable: Iterable<T>,
    reducer: (previousValue: T, currentValue: T, currentIndex: number, iterable: Iterable<T>) => T,
initialValue?: T
): T;

It has the same return type as it's input (T). The trouble comes when assigning the type back unto itself. Typescript doesn't (and shouldn't) know which type to use.

One solution is to type check before using reduce, with a type guard like so,

const isNumberArray = (arr: unknown[]): arr is number[] => {
  for (let i = 0; i < arr.length; i++) {
      const element = arr[i]

      if (typeof element !== 'number') {
          return false
      }
  }

  return true
}

Playground

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda