0

Hi I want to write a generic function to determine primitive type of array. but I'm having an issue with it and couldn't find a similar solution to my problem. this is my function:

export function isGenericTypeArray<T>(value: any): value is T[] {
  // dont use on classes!!!!!!!!!!!!!!!!!!!!!!
  if (Array.isArray(value)) {
    let somethingIsOfType = false;
    value.forEach(function (item) {
      if (typeof item !== typeof T) {
        console.log("array isn't of matching type!");
        return somethingIsOfType; // false
      }
    });
    somethingIsOfType = true;
    return somethingIsOfType; // true
  }
  console.log("this isn't an array");
  return false;
}

the error is with if (typeof item !== typeof T) I get 'T' only refers to a type, but is being used as a value here.ts(2693)

i've seen this post text but didn't understand.

I've seen this post text but didn't understand.

IdoS99
  • 11
  • 3

1 Answers1

0

T is a type parameter and does not exist at runtime as a value, and therefore you cannot check typeof T. A solution could be to pass the type as a function parameter and use instanceof to check that the type is matching. For example:

export function isGenericTypeArray<T>(value: any, type: new () => T): value is T[] {
    // dont use on classes!!!!!!!!!!!!!!!!!!!!!!
    if (Array.isArray(value)) {
        let somethingIsOfType = false;
        value.forEach(function (item) {
        if (!(item instanceof type)) {
            console.log("array isn't of matching type!");
            return somethingIsOfType; // false
        }
        });
        somethingIsOfType = true;
        return somethingIsOfType; // true
    }
    console.log("this isn't an array");
    return false;
}

An example of usage, given the type Animal, is:

isGenericTypeArray(arr, Animal);
Jacques Marais
  • 2,666
  • 14
  • 33