When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected.

import 'reflect-metadata'
function logType(target : any, key : string) {
     var t = Reflect.getMetadata("design:type", target, key);
     console.log(`${key} type: ${t.name}`);
   }
export class Demo {
  @logType // apply property decorator
  test: Date;
}
let demo = new Demo();
console.log(Reflect.getMetadata('design:type', demo, "test"));

However, when I incorporate this same code into an Angular 2 Project, it returns "function Object() { [native code] }" instead.

I have created a Plunker to demonstrate this: https://plnkr.co/edit/DhXT89U0q5fCOWlCrx6w?p=preview

Despite this issue, Reflect.getMetadata('design:type' ...) still functions correctly with custom classes and other builtin classes. The problem only arises with Date objects.

Can you help identify what mistake I am making?

Answer №1

Make sure to properly execute the function, don't just leave it hanging there :), remember to include parentheses after @logType

export class Demo {
  @logType() // don't forget to add parentheses 
  test: Date;
}

Alternatively, you need to update your @logType function to something similar to this:

function logType(type: any) {
  return function(target: any, propertyKey: string) {  
     Reflect.defineMetadata('design:type', type, target, propertyKey);
  }
}

This is how you can use it:

export class Demo {
  @logType(Date) // apply property decorator
  test: Date;
}

I have made changes in the plnkr to demonstrate what I am talking about: plnkr

The default types you can get are either string, boolean, number, or object. The built-in types like Date, Array, or even custom classes like Math and WeakMap will all evaluate to Object. This might be a bug or intentional design.

If you want to get custom classes using your method, you can do something like this:

export class Demo {
  @logType
  test: Demo;
}

It will display Demo in the output.

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

Transmitting language codes from Wordpress Polylang to Angular applications

I am currently attempting to manage the language settings of my Angular application within WordPress using WordPress Polylang. To achieve this, I have set up the following structure in my Angular application: getLanguage.php <?php require_once(". ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

Exploring Angular Testing with SpyOn

Apologies for my inexperience with Angular, but I am struggling with using spyOn in a unit test. In my unit test, there is a method on the component that calls service1, which in turn calls another service2. However, when I try to spyOn service1 in order ...

Similar to `util.inspect` in Node.js, Deno also has a function

Is there a utility function in Deno that can stringify an Object or primitive similar to Node.js util.inspect? For instance, if I have a JSON object in Node.js and want to display its contents: > m = {k1:'v1', k2:'v2'} { k1: ' ...

Guide on integrating a personalized theme into your Ionic 5 app

I'm looking to customize the theme of my Ionic 5 app by adding a red-theme to variables.scss @media (prefers-color-scheme: red) { :root { --ion-color-primary: red; Afterwards, I attempted to initialize it in index.html <meta name=" ...

Angular: The metadata version does not match for the module located in src/app/app.module.ts. A version of 3 was found when version

Recently, I made the transition from Angular 4.0.0 to 5.2.0. However, after implementing the recommended changes, I encountered a perplexing error message: ERROR in Error: Metadata version mismatch for module /home/khalidvm/Desktop/Workspace/Front/Migrat ...

Send information to the main application component

Can data be passed two or more levels up from a Child Component to the App Component? https://i.stack.imgur.com/JMCBR.png ...

Guide to incorporating Angular 2 code into your Rails application

As a beginner in Ruby on Rails, I have recently learned some CRUD functionalities with RoR. Additionally, I am just starting my journey with Angular 2 and currently learning the basics. I noticed that RoR has its own HTML template engine similar to Angula ...

The connection named "Default" could not be located for use with TypeOrm and Express

I am currently facing an issue with my setup involving TypeORM. It seems that Express is being initialized before the connection to the database is established with TypeORM, causing an error message "Connection default not found." Here is a snippet of the ...

An error has occurred while attempting to differentiate '[object Object]'. In Angular, only arrays and iterables are permitted for this operation

Can someone help me with resolving the error I am encountering while trying to display data on the front end? service.ts rec_source(){ var headers = new HttpHeaders().set('Authorization', 'Token ' + localStorage.getItem('u ...

Deactivate multiple input fields by utilizing various radio buttons

I need help with enabling and disabling input fields based on radio button selection. When the first radio button is selected, I want to disable three input fields, when the second is selected, only two specific input fields should be enabled (SHIFT START ...

Using conditional data binding in Angular 2 allows for dynamic rendering based

Here is the code I am using to display images from a database: <div *ngfor='let pad of pictures' class=""> <img class="activator" src="imagepas/{{pad.picturefirst}}"> </div> Sometimes in the database, there may no ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Angst with the Angular Command Line Interface

After installing the Angular CLI via the command prompt, I encountered an error related to @angular-devkit/build-angular. However, everything else seems to be working fine. Does anyone have any ideas as to why this might be happening? https://i.stack.im ...

Guide to iterating through different endpoints in a predetermined sequence

I am facing a challenge with testing various endpoints using different login credentials. When looping through the endpoints, the results are not appearing in the sequential order due to asynchronous nature. My goal is to iterate through each endpoint wit ...

Implementing the breadcrumb component within dynamically loaded modules loaded through the router-outlet component

I'm currently working on an angular 8 breadcrumb component for my application. The requirement is to display it in the content of the page, not just in the header, and it should never be located outside the router-outlet. This has posed a challenge fo ...

Why is my Angular2 *ngFor not showing the contents of my array?

Currently delving into Angular 5 and immersing myself in a crash course. I've managed to progress past just using an ngFor directive, but as I tackle part of a practice assignment, I'm encountering an issue where the data won't loop and disp ...

How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class: class Dataframe extends Object { _nrow: number; _ncol: number; _identity: number[]; co ...

What causes a typed string literal to be recognized as a pure string in TypeScript?

Consider the TypeScript code below: type example = 'BOOLEAN' | 'MULITSELECT' | ''; interface IObjectExample { a: string, readonly b: example } const handleObj = (obj: IObjectExample) :void => { console.log(&ap ...

Enhance your material-ui component using TypeScript functionality

Exploring ways to enhance the Material-ui Button component by introducing new props. The objective is to introduce a new prop called fontSize with three size options - small, medium, large. <Button variant="outlined" color="primary" ...