What is the method to retrieve the data type of an array in TypeScript?

I am currently working on a TypeScript function (still getting acquainted with TS) that accepts a parameter which could be either a number, a string, an array of numbers, or an array of strings.

It is crucial for me to distinguish between these 4 types within my code.

When I use typeof on an array, it always returns 'object'. How can I differentiate between an array of strings and an array of numbers in my code?

I understand that I could utilize for loops or array methods to determine the type of each element in the array, but I am wondering if there is a more elegant solution.

function numToLet(input: number | number[] | string | string[]) {

if (typeof input === 'number') {
    console.log(`The input ${input} is a number.`)
}

if (typeof input === 'string') {
    console.log(`The input ${input} is a string.`)
}

if (typeof input === 'object') {
    console.log(`The input ${input} is an object. Not sure about its specific type though ¯\_(ツ)_/¯`)
}

}

Answer №1

Have you explored the Array method known as Array.isArray()? It can be found at this link. I tend to use it quite frequently, perhaps even excessively.

In a previous project where strict mode was not enabled, I found Array.isArray() to be incredibly useful in handling both null values and unexpected inputs.

const myActualArray = ['apple', 'banana'];
const myUnArray = "apples and bananas";
let oops;

console.log(Array.isArray(myActualArray)); // true
console.log(Array.isArray(myUnArray)); // false
console.log(Array.isArray(oops)); // false
console.log(Array.isArray(null)); // false

On another note, have you delved into TypeScript generics? I'm just beginning to explore them myself, so I cannot confidently say if they offer a suitable TypeScript solution for your needs - keep in mind that Array.isArray() is specifically a JavaScript solution. You can learn more about TypeScript generics here.

An additional point to consider after reading your comment: It appears that you are relying heavily on your code to handle one of four input types. By combining the utilization of typeof with Array.isArray, you can streamline this process.

function numToLet(input: number | number[] | string | string[]) {

  if (typeof input === 'number') {
      console.log(`Input ${input} is a number.`)
  }

  if (typeof input === 'string') {
      console.log(`Input ${input} is a string.`)
  }

  if (Array.isArray(input)) {
      // If you're confident that your array consists solely of either all numbers or all strings, simply check the type of the first element.
      if (typeof input[0] === 'number') {
        console.log(`Input ${input} is a number.`)
      }

      if (typeof input[0] === 'string') {
        console.log(`Input ${input} is a string.`)
      }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to establish the adjacency of 2 elements within a 2D array

Trying to figure out how to determine if an element is adjacent to another in a two-dimensional array that is not sorted. For instance, when testing myArray[2,2] using my comparison function, I want true to be returned for input equal to the elements at po ...

The module './product' could not be located, resulting in error TS2307

app/product-detail.component.ts(2,22): error TS2307: Cannot find module './product'. I have tried several solutions but none of them seem to work for me. I am working on a demo app in Angular 2 and encountering this specific error. Any guidance ...

Numpy: Adding values to specific elements of an array based on the provided indices for incrementing

I am currently attempting to convert a second-order tensor into a binary third-order tensor. The challenge involves taking a second-order tensor represented as an m x n numpy array (A) and replacing each element value (x) in A with a vector (v). This new v ...

Exploring Ternary Functions within an Associative Array in PHP

I am curious about the possibility and potential lack of side effects when assigning associative array elements using a ternary function in PHP. Instead of the traditional method: $second_element = $test ? "tistrue" : "tisfalse"; echo build_assignment_pa ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...

The fixed method in JavaScript is a handy tool for converting

Is it possible to implement the toFixed() method only when the input strings exceed 12 characters in length? If not, I would like the input to display normally, resembling a standard calculator app. I have experimented with a maximum character method, but ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

Trigger the component to emit an event once all validators have been cleared

I have developed a unique custom input element that showcases its label when a required constraint is present (calculated in the OnInit method). @Component({ selector: 'custom-input', template: `<div *ngIf="isMandatory()">Mand ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

What is the best way to invoke a function with a variable number of arguments?

I am struggling with passing each element of an array as parameters to a function. For example: $myArray = array("element1","element2","element3"); //Pass each element as a new parameter to a function myFunction($element1, $element2, $element3); //If th ...

Implementing dynamic checkboxes in a design based on the length of a JSON array

I am looking to incorporate a dynamic checkbox within a linear layout that adjusts its size based on the JSON array retrieved from an API. The response from my API looks like this: [ { "id": 1, "alertName": "Device" }, { "id": 2, "alertName": "Email" } ] ...

Angular - What causes variables to lose data after component changes?

Having an issue with two components - one creating and changing an array, and the other getting the array. The problem is that when retrieving the array in the second component, it only shows the default empty data. Code for array creation: export cla ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

What is the method for incrementing each column in a numpy array by a fixed value?

I'm facing some difficulties when trying to add a constant value to every alternating column in a numpy array. For instance, let's assume that I have an array filled with zeros as follows: import numpy as np a = np.zeros([100,10], dtype=np.in ...

What is the best way to forward all URLs to one central page?

I've recently started working with Angular and I'm currently developing a web app project using Angular 9. I could really use your help with this. My goal is to have a dynamic URL structure for the web app, such as https://www.myMainURL.com/***, ...

Creating a hyperlink dynamically within an Angular TypeScript file can be easily achieved

I am looking to create a dynamic hyperlink within the component (in the .ts file) using a for loop inside a function. I understand that this can be achieved by utilizing *ngFor loop in the template. For instance - <div *ngFor="let rec of item.R ...

What is the best way to organize tableview cells into alphabetical sections with a customized header cell?

In my CartVC, I have data being passed from another ViewController through a closure to populate the cells successfully. Now, I am attempting to organize these cells into sections based on their brand in the CartVC. However, all the data seems to be gettin ...

Uploading various arrays of objects from JavaScript to MVC

Struggling with posting multiple arrays of objects to MVC? I've found solutions for posting one array, but it seems I'm missing something small. Here's the JS code I'm using: $.ajax({ type: "POST", url ...

Finding the middle and highest value in an array using PHP

I need to establish a dynamic upper limit for an array, with the lower limit always set at 0. The array values can vary greatly, ranging from 1 to 5, 100 to 500, or even into the thousands. Instead of using a constant value like max($array) + 100, I woul ...

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...