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")
}
}
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.
The isArray() method returns true if an object is an array, otherwise false .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With