Struggling to interpret the output of decorators when working with TypeScript

I'm struggling to grasp this code:

function Logger(target) {
  console.log('The decorated class:', target);
}

@Logger
class SampleClass {
  constructor() {
    console.log('Hey!');
  }
}

When I compiled and ran it using Node, the output was

The decorated class [Function: SampleClass]
. Why didn't I see Hey!? Can someone help me understand this code? I saved it as

decorators.ts

I compiled it with tsc --target ES5 --experimentalDecorators decorators.ts and then ran node decorators.js

The documentation is too complex for me to decipher

I am completely confused - in Angular we don't have to instantiate a class and everything still works fine, but here we do. Can someone please explain why there's no need to instantiate a class in TypeScript?

Answer №1

The console.log('Hey!') statement can be found within the constructor of the SampleClass. However, no instances of SampleClass have actually been created. Instead, only the class object itself has been modified.

It's worth noting that a class decorator does not automatically trigger the constructor of the decorated class unless you explicitly instantiate it.


To see the desired output of "Hey!", consider adding new SampleClass() at the end of your code snippet.

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

After the transition to Angular 8, the functionality of testing with Jest seems to have

After upgrading our Angular version from 7 to 8, we encountered some issues when using Jest as our test runner. Our main objective now is to ensure that our build pipeline runs smoothly with our JavaScript tests. One error message we're facing is: An ...

Sample test scenario for a service function that includes an HTTP subscription using Angular's HTTP RxJS

I have a service method that includes an HTTP call and subscribes immediately to the response code in order to execute the rest of the action command based on it. Here is an example of the service method: processData(id): void { const url = `http://l ...

Using RxJS switchMap in combination with toArray allows for seamless transformation

I'm encountering an issue with rxjs. I have a function that is supposed to: Take a list of group IDs, such as: of(['1', '2']) Fetch the list of chats for each ID Return a merged list of chats However, when it reaches the toArray ...

gyp ALERT: Received a warning of EACCES when attempting to install angular/cli

Working on Ubuntu 17.04 with Node 8.9.4 LTS installed, I encountered an error loop while trying to install Angular CLI using npm. gyp WARN EACCES user "root" does not have permission to access the dev dir "/usr/lib/node_modules/@angular/cli/node_modules/n ...

Having trouble with the Bootstrap 4 toggle functionality while converting a Bootstrap theme to an Angular 9 project?

I am currently in the process of converting a Bootstrap theme to an Angular 9 project. I have successfully configured all the necessary JS and CSS files in the angular.json file, but unfortunately, the toggle function is not working. Please take a look at ...

Arrange the "See More" button in the Mat Card to overlap the card underneath

I'm currently working on a project that involves displaying cards in the following layout: https://i.stack.imgur.com/VGbNr.png My goal is to have the ability to click 'See More' and display the cards like this: https://i.stack.imgur.com/j8b ...

Drag-and-drop functionality in Angular JavaScript Tree View for rearranging nodes and inserting new nodes

Exploring the world of JavaScript Tree Views and Angular as a beginner. After scouring the internet for information, I'm struggling to find a solution to my specific query. Looking for a tree-view component that seamlessly integrates with Angular, c ...

Can React provide names for its own built-in components?

Background When working in React, you have the ability to use a variable for a component constructor, as demonstrated by the example code below with ComponentToRender. import { Badger, Mushroom } from './components'; const renderBadger = true; ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...

The TypeScript feature Array.find may potentially return undefined, yet it is always treated as a specific data type

There's a minor obstacle blocking my way: const foo = ["foo", "bar"]; // type "string[]" const foundFoo = foo.find(fooEl => fooEl === "notFooBar"); // type "string" -> why not "string | unde ...

Creating a customized pagination feature in Angular 8 without relying on material design components

I am looking to implement pagination in my Angular 8 project without relying on any material library. The data I receive includes an array with 10 data rows, as well as the first page link, last page link, and total number of pages. Server Response: { ...

Numeric Data Entry Format

I'm dealing with two inputs: one called "before" and the other called "after". When a value is entered in the before input, the value in the after input will be before / 1000 which means there might be 3 or more decimals at times. How can I displ ...

Determine whether there are three or more identical values when comparing two objects in typescript

Hello there, I am in need of some assistance as I am unsure where to begin. Any help would be greatly appreciated. Here are the two objects I have: const Questions = { five: "c" four: "c" one: "a" three: "a" two ...

Displaying buttons on each row in an ngx-datatable based on a condition using *ng

In my table, there is a column with a hidden element that appears when a show button is clicked. Currently, clicking the button reveals all hidden fields at once. I want to modify this so that only the input field for the specific row appears when the butt ...

Cast the variable to access nested data

I'm currently working with data retrieved from an API call in the form of nested objects. My goal is to extract and organize this information for display in a table. In my code, I am using a loop with for (const [key, value] of Object.entries(result)) ...

Link a template to a formly field when clicking on another field within an Angular formly form

Recently, I have been utilizing a Formly form that includes a section for displaying dynamic HTML content. Within this form, I am using the template field to initialize some HTML content when the page loads. However, I have encountered an issue where chang ...

angular triggering keyup event multiple times

Currently, I am working on a datalist feature. Whenever the user types something into the input field and releases a key, a GET request is made to retrieve an array of strings which are then displayed in the datalist. <input type="text (keyup)=&quo ...

Could someone assist me in identifying the issue with this logfile and guiding me in the correct direction?

Can someone help me troubleshoot the ng e2e issue in my code? Here's a screenshot of the log file: https://i.sstatic.net/PCrab.png I apologize for the formatting of the package.json file. `package.json` file: { "name": "planning", "version": "0. ...

Why does the type checking for props in vue.js keep failing despite my use of "Object as PropType<GeographicCoordinate | null>"?

Scenario: Utilizing vue.js (^3.2.13) with Typescript and Composition API in Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: numb ...