Can we determine the anticipated data type for members of an array in TypeScript?

I'm curious about determining the expected type of a typed array:

let A1:string[] = [],
    A2:Date[] = [],
    expectedType = (arr:any[]) => {
       console.log("Expecting: " + /*some magic*/);
    };

expectedType(A1); // prints string
expectedType(A2); // prints Date

UPDATE: As mentioned in the response, currently there isn't a way to know the declared types of array members in TypeScript. However, you can implement something like this:

class StrictArray extends Array {
    private _expectedType: {new(): T}; // constructor type definition
        get expectedType():{new(): T} {return this._expectedType;};
        constructor(ctype: {new(): T}, args?:any) {
             super.constructor(args);
        }

//...
        push(t:any) {
            if (!(t.constructor !== this._expectedType))
                throw "Not valid type";
            return super.push(t);
        }
    }

Now we have objects that act like regular arrays, but we can access and manage their members' types.

Applying it to our example:

let A1:StrictArray = new StrictArray(string),
    A2:StrictArray = new StrictArray(Date);

    /*magic = */
    A1.expectedType.name; // prints string
    A2.expectedType.name; // prints Date

Not sure about the practicality or drawbacks of this approach, feel free to share your thoughts.

Answer №1

Is it possible to predict the data type of array elements in TypeScript?

Unfortunately, it is not possible. Type information is stripped away during compilation to JavaScript, so you are left with only what JavaScript provides. You can try using JavaScript-style introspection like typeof arr[0] === 'string', but keep in mind that JavaScript has its limitations.

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

Angular firing off select option with object properties

Within my Angular application, I am faced with a situation involving a <select> element that contains a list of <option> elements whose values are associated with objects. My goal is to capture the last selected value using the following code: ...

Vue Error: The method "reduce" is not a function

Currently implementing Vue.js with Typescript and aiming to utilize reduce for summing up the values of desktopCnt and mobileCnt from the deviceCount array to display their total numbers. The deviceCount array structure is as follows: [ { " ...

When attempting to INSERT a JSON Array using the json_to_recordset() function, an error message "Column Does Not Exist" is displayed

Encountering a challenge while attempting to insert variable data from a JSON array into a Postgresql table. The goal is to insert two variables, link_url and link_key, into their respective columns. Utilizing json_to_recordset() method to extract the var ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

Deploying a Node.JS Express API containerized with Docker on the Amazon Web Services Cloud

Throughout my experience as a student developer, I have exclusively used the Firebase suite and deployed my express apps as callable endpoints using Firebase Functions. Lately, I've been interested in delving into AWS, Docker containers, and SQL data ...

I am in the process of transitioning my JSX website to TSX and am struggling to figure out the proper placement of my type definitions

As the title suggests, I am in the process of migrating an application that I developed using the Google Maps API for rendering maps. In this app, I display information on maps and include functionality to zoom in when a user clicks on something. The erro ...

Styling pagination in Angular 8 PrimeNG p-table

I'm having an issue with PrimeNG where my paginated table is displaying without proper styling. I want it to look like the one in this stackblitz example. I believe I have installed all the necessary packages and configured the styles paths in the ang ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Exploring the concept of rest arrays within a destructured object

Is there a way to declare c as an optional array of any type in this code snippet? const a = ({ b, ...c }: { b: string, c: ? }) => null ...

Verify if TypeScript object contains a specific key dynamically without the need for a custom type guard

Using TypeScript's in keyword allows us to check if an object contains a specific key in a type-safe manner when the key is defined as a string literal: function guardHasTest <Data extends object> ( value: Data ): Data & Record<'te ...

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...

Tips for Wrapping Page Layouts and Routes in Angular 4

As I work with my regular angular 4 app, I often find myself using Router, ActivatedRoute.params.subscribe, [routerLink], and other tools to navigate between pages and interpret URLs. This results in a multitude of "magic strings" scattered throughout var ...

Retrieve particular key from document in MongoDB based on provided value

My Document retrieval process looks like this: async findOne(id: string) { return await this.gameModel.findById(id); } async update(id: string, updateGameDto: UpdateGameDto) { const game = await this.findOne(id) // This code snippet prints al ...

Utilize an exported class as a type within a .d.ts file

I have two classes, ./class1.ts and ./class2.ts, with the following structure: export class Class1{ ... } and export class Class2{ ... } In my file ./run.ts, there is a function that accepts a class input function doSomething(klass: ClassType){ l ...

Tips for utilizing ngModel with dynamic setter/getter properties

Currently, I am engaged in a project where users can generate applications dynamically. In order to achieve this, I allow components to specify their own properties as shown below. export class InputComponent extends GenericComponent implements OnInit { ...

Displaying a pop-up window on top of a Google Map in Angular 5

Currently, I am engrossed in a small project that involves the utilization of Google Maps JS API (latest version). The front end is constructed on Angular 5 with Typescript. My goal is to display a modal window over the map as soon as the user clicks anywh ...

Static files compiled from Django 2 and Angular 6 consistently redirect to the static directory

I am currently working on a Django 2 + Angular 6 project. As part of my build process, I move the compiled JS files into Django's static folder. However, I encounter an issue whenever I try to access a link, such as , the browser automatically redire ...

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

The menu functionality is not responding when I try to access it by tapping on the screen using Ionic

After logging in, my single screen contains a home menu with four tabs: home, about, location, more. The menu functions properly in this setup. To navigate to the home page with all tabs and the menu after login, I use the following code: this.navCtrl.push ...