Discovering Typescript's property data type using reflection during program execution时间。

After transpiling TypeScript code to JavaScript, it is commonly understood that TypeScript type information gets lost and features such as reflection become very restricted. Since we rely on JavaScript reflection at runtime, the level of understanding regarding TypeScript types is understandably limited.

Is there a way to access TypeScript type information during runtime?

Consider the following code snippet from codepen.io:

class Book {
    public title: string;
    public isbn: string;
}

class Author {
    public name: string = '';
    public books: Book[] = [];

    constructor() {
        const r = Reflect.getOwnPropertyDescriptor(this, 'books');

        console.log(`typeof: ${typeof this.books}`);
        console.log(`constructor: ${this.books.constructor.name}`);
        console.log(r);
    }
}

const author = new Author();

The logs display "object", "Array" and:

Object {
    configurable: true,
    enumerable: true,
    value: [],
    writeable: true
}

The goal is to loop through Author properties and determine the type of Author.books or any other property dynamically. The aim is to be able to recognize that Author.books is an Array of Books during runtime. Merely identifying it as an object or array does not fully serve this purpose at all.

Does anyone have any suggestions on how this can be accomplished?

Answer №1

In my humble opinion, I don't believe it can be achieved using the default options available to you - you'll need to delve into the d.ts to truly reflect all the types.

As mentioned; the array is simply an instance of Array, so the only way to determine what type the array should contain is by specifying the class of the desired type. Therefore, you could potentially attempt something similar to this:

class Book {
  public title: string;
  public isbn: string;
}

type Newable<T> = {
  new (): T;
}

class Author<T> {
  public name: string = '';
  public books: T[] = [];

  constructor(bookRef: Newable<T>) {
    console.log(`name: ${bookRef.name}`);
  }
}

const author = new Author(Book);

Although not optimal, this method will only function if Book is a class.

In addition, typescript is capable of deducing the type used for Book based on what you provide to the constructor:

https://i.sstatic.net/Jp4OW.png

bookRef.name will retrieve the class name during runtime.

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

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

Utilize Typescript to generate an object that contains a partial interface

Seeking assistance with an issue. We are working with two interfaces: interface IUserEntity { Id: number; FirstName: string; LastName: string; } interface IUserEntityMethods { GetFullName(): string; } I am trying to create an object tha ...

The projection of state in NGRX Store.select is not accurately reflected

Every time I run the following code: valueToDisplay$ =store.select('model','sub-model') The value stored in valueToDisplay$ always corresponds to 'model'. Despite trying various approaches to properly project the state, it s ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

Conceal or eliminate webpack from Angular 2 framework

Currently immersed in an Angular 2 project with TypeScript. Desiring to conceal or eliminate webpack from the developer tool. Came across information about uglify but it remains somewhat puzzling. See the image below for a glimpse of the Chrome Developer ...

`Property cannot be redefined: __internal__deprecationWarning` detected in a Shopify Hydrogen development project

Recently, while working on my Shopify Hydrogen project using Remix and Typescript, I encountered a sudden error when running npm run dev. Everything was functioning perfectly just 5 hours ago, but after returning from dinner, the app refuses to launch. ╭ ...

Typescript encountering difficulty in accessing an array saved in sessionStorage

Imagine you have an array stored as a string in session storage, and you need to retrieve it, add an element, and then save it back. trackNavHistory = (path: String) => { let historyArr : Array<String> = sessionStorage.getItem("navHistory ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

A guide on how to navigate to a customizable element in React Native

After creating a glossary, I needed a way to access the content of a specific letter by clicking on that letter from a list displayed at the top of my page. However, I encountered an issue - while I managed to implement scrolling functionality, I couldn&ap ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Is there a workaround for utilizing reducer dispatch outside of a React component without relying on the store?

Recently, I implemented a reducer in my project that involves using react, typescript and nextJS. I am wondering if there is a method to trigger the reducer outside of a react component, such as from an API service. While searching for solutions, most re ...

Join the Observable and formControl in Angular 4 by subscribing

My goal is to display the data retrieved from FireStore in the screen fields upon loading. However, the buildForm() function is being called before subscribing to the data, resulting in the failure to populate the screen fields with the FireStore data. pe ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. Th ...

Can someone guide me on creating a slideshow using Ionic?

Having trouble integrating a javascript/css slideshow into Ionic. Ionic does not support the use of ".style" in elements. Need assistance, below is the code: <head> <title>Slideshow</title> <style> .slides {display:none;} </styl ...

Generating an instance of a class by using the class name as a string

Before jumping to conclusions, please take a moment to read the following: In addition to TypeScript, my issue also involves Angular2. Main Goal I am in need of a method in app.component.ts that can take a string (Class Name) and generate an instance of ...

Utilize Knex to retrieve data from the req.query

express and knex have been giving me some trouble; I am struggling to get this endpoint working using req.querys (response from express), even though it worked fine when I used req.params. Express: app.get(`/actor`, async (req: Request, res: Response) =&g ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...