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

69
Visualizações
Reading the generic type and doing some logic based on it

I am reading a few arrays from env variables, and some of them should be number[] and some should be string[]... I am trying to write a function which can process both(and maybe more in the future) types of arrays and convert them to the proper values...

So I have 2 env variables which look like this:

STR_ARR="tst1,tst2,tst3"
NUM_ARR="1,2,3"

And here's the function with some pseudo code:

function parseArray<T>(arrStr: string, minLength: number = 1): T[] {
  const arr = arrStr.split(',');

  if (arr.length < minLength) {
    throw new Error('Array is not of required length');
  }

  // if (T is number) {
  //   ... convert all elements to number and return number[];
  // } else if (T is string) {
  //   ... check if all string elements are of required length and return string[];
  // }

  return arr;
}

One solution I guess would be to just send the type of array I want as a function parameter, but that doesn't seem very "typescript-y", so I am looking for some alternatives.. Thanks!

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

0

TypeScript does not exist at runtime - it all compiles down to JavaScript - so you can't use type parameters in the logic of your function to return the correct array type. Just think about how you would have to implement this if there was no TypeScript. The function needs to know what type you want back so you must pass it as a parameter, there's no getting away from that and no alternatives.

What TypeScript will allow us to do is clearly tie the type parameter of the function to its return type. You hinted you already had an idea how to do this but here is how I would approach it using function overloads:

type ParseTypes = "string" | "number";

function parseArray(type: "number", arrStr: string, minLength?: number): number[];
function parseArray(type: "string", arrStr: string, minLength?: number): string[];
function parseArray(type: ParseTypes, arrStr: string, minLength: number = 1): unknown[] {
  const arr = arrStr.split(',');

  if (arr.length < minLength) {
    throw new Error('Array is not of required length');
  }

  // if (type === "number") {
  //   ... convert all elements to number and return number[];
  // } else if (type === "string") {
  //   ... check if all string elements are of required length and return string[];
  // }

  return arr;
}

const asStr = parseArray("string", "1,2,3"); // string[]
const asNum = parseArray("number", "1,2,3"); // 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