Categories
TypeScript Answers

How to test for array of string type in TypeScript?

Spread the love

Sometimes, we want to test for array of string type in TypeScript.

In this article, we’ll look at how to test for array of string type in TypeScript.

How to test for array of string type in TypeScript?

To test for array of string type in TypeScript, we can use the Array.isArray and the array every instance method.

For instance, we write

const isArrayOfStrings = (value: any): boolean => {
  return (
    Array.isArray(value) && value.every((item) => typeof item === "string")
  );
};

to call Array.isArray to check if value is an array.

And we use

value.every((item) => typeof item === "string");

to check if every item in value is a string with value.every.

Conclusion

To test for array of string type in TypeScript, we can use the Array.isArray and the array every instance method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *