Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the type of an array?

Is there a way to check what the array "type" is? for example

Array<string> means it is a collection of "string" type variables.

so if i create a function

checkType(myArray:Array<any>){
  if(/*myArray is a collection of strings is true*/){
    console.log("yes it is")
  }else{
    console.log("no it is not")
  }
}
like image 830
Newbie2016 Avatar asked Apr 13 '17 16:04

Newbie2016


People also ask

What is the type of an array in JavaScript?

Arrays are just regular objects In Javascript, there are only 6 data types defined – the primitives (boolean, number, string, null, undefined) and object (the only reference type). Arrays do not belong to this list because they are objects as well.

How do you check if it's an array in JavaScript?

The isArray() method returns true if an object is an array, otherwise false .

How do you check if an element is in an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.


1 Answers

The type system that typescript offers doesn't exist at runtime.
At runtime you only have javascript, so the only way to know is to iterate over the array and check each item.

In javascript you have two ways of knowing a type of a value, either with typeof or instanceof.

For strings (and other primitives) you need typeof:

typeof VARIABLE === "string"

With object instance you need instanceof:

VARIABLE instanceof CLASS

Here's a generic solution for you:

function is(obj: any, type: NumberConstructor): obj is number;
function is(obj: any, type: StringConstructor): obj is string;
function is<T>(obj: any, type: { prototype: T }): obj is T;
function is(obj: any, type: any): boolean {
    const objType: string = typeof obj;
    const typeString = type.toString();
    const nameRegex: RegExp = /Arguments|Function|String|Number|Date|Array|Boolean|RegExp/;

    let typeName: string;

    if (obj && objType === "object") {
        return obj instanceof type;
    }

    if (typeString.startsWith("class ")) {
        return type.name.toLowerCase() === objType;
    }

    typeName = typeString.match(nameRegex);
    if (typeName) {
        return typeName[0].toLowerCase() === objType;
    }

    return false;
}

function checkType(myArray: any[], type: any): boolean {
    return myArray.every(item => {
        return is(item, type);
    });
}

console.log(checkType([1, 2, 3], Number)); // true
console.log(checkType([1, 2, "string"], Number)); // false


console.log(checkType(["one", "two", "three"], String)); // true

class MyClass { }
console.log(checkType([new MyClass(), new MyClass()], MyClass)); //true

(code in playground)

like image 103
Nitzan Tomer Avatar answered Jan 03 '23 23:01

Nitzan Tomer