Home > Software design >  Accept more than one array type in Generic Typescript
Accept more than one array type in Generic Typescript

Time:08-31

I am using helper object to check types of variables. But i have faced a problem with types. I have a generic array: <T, V>(val: V | T[]): val is T[] => R.is(Array, val). Using this approach i am trying to avoid using any. This generic works well until val can be, for example, string[] or number[]. Example:

const a = (b: string[] | number[] | string ) => {
  is.array(b)
}

In this case generic captures only the first possible array type and checks it. I am attaching a link to codesandbox with the illustration of issue. Please, help

enter image description here

CodeSandBox

CodePudding user response:

Use Array.isArray :

function f(b: string[] | number[] | string) {
  if (Array.isArray(b)) {
    // b: string[] | number[]
  } else {
    // b: string
  }
};

Its declaration:

function isArray(arg: any): arg is any[];

Own typeguard implementation:

function isArray(arg: any): arg is any[] {
  return arg !== null && typeof arg === "object" && "length" in arg;
}

Rambda solution:

function array(arg: any): arg is any[] {
  return R.is(Array, arg);
}
  • Related