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

170
Visualizações
Can I change the type of the accumulator on the .reduce method?

I'm currently trying to reduce a string into number[], but I'm new to typescript and simply couldn't figure out how to type my code so that the typescript compiler would stop complaining...

What I'm trying to do:

matString.split(/[\n ]/).reduce((acc, cur, index) => acc[index] = Number(cur));

So far, I have tried typing it like this, but it just won't work :(

matString.split(/[\n ]/).reduce((acc: Array<number>, cur, index) => acc[index] = Number(cur)) as Array<number>;

Just for context, this code is receiving a matrix in the format of a string and I want to convert it down to an array so that I can work with it. I have already encountered this issue under different circumstances and had to work around it, but this time I would like to understand how to fix it.

Also, if it does help explain my issue better, here's a picture of my code followed by the compiler's error: code image with error

This is part of my solution to this exercise on exercism.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

While it's possible, it'd be far easier to avoid .reduce and just map the split string to Number, no explicit typing necessary:

const result = matString
  .split(/[\n ]/)
  .map(Number);

If you had to go the .reduce route, use generics to indicate the accumulator type, and remember to return the accumulator at the end of the callback:

const result = matString.split(/[\n ]/).reduce<Array<number>>((acc, cur, index) => {
    acc[index] = Number(cur);
    return acc;
}, []);

If the input is composed of a string that contains numeric characters, it might be better to match those characters, instead of splitting on newlines and spaces:

const result = matString
  .match(/\d+(?:\.\d+)?/g) // assuming there will always be at least one match
  .map(Number);
about 4 years ago · Juan Pablo Isaza 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