Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

67
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda