Home > Enterprise >  Reading the generic type and doing some logic based on it
Reading the generic type and doing some logic based on it

Time:09-23

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!

CodePudding user response:

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[]
  • Related