Issues with the execution of Typescript decorator method

Currently, I'm enrolled in the Mosh TypeScript course and came across a problem while working on the code. I noticed that the code worked perfectly in Mosh's video tutorial but when I tried it on my own PC and in an online playground, it didn't work as expected. Since I'm not very familiar with this topic, I am unsure of what mistake I may have made in my code.

If anyone has any insights or helpful suggestions, please feel free to comment below and let me know what might be causing the issue in my code.

function Log(target: any, methodName: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value as Function;

  descriptor.value = function (...args: any) {
    console.log("before");
    original.call(this, ...args);
    console.log("after");
  };
}

class Person {
  @Log
  say(message: string) {
    console.log("Person says " + message);
  }
}

let person = new Person();
person.say("hello");

Answer №1

Uncertain about what you mean by not functioning, but if you input your code into the typescript playground, you may encounter the following issue...

An error occurs when trying to resolve the method decorator signature as an expression.
  The decorator is expected to receive 3 arguments, but it only receives 2 during runtime.
'target' and 'methodName' variables are declared but remain unused.

If you adjust the experimentalDecorators flag in the tsconfig.json, the code will run correctly. You can view it in action on the playground. As mentioned in the typescript documentation...

Decorators are a feature of the language that has not yet been officially included in the JavaScript specification. This means that there may be differences between TypeScript's implementation and JavaScript's implementation determined by TC39.

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

Vue - Additional loading may be required to manage the output of these loaders

Currently working with Vue and babel. I have a function that's been exported // Inside file a.js export async function get() { ... } I am trying to link this exported function to a static method of MyClass // Inside file b.js import myInterface fr ...

The Jest test is experiencing a failure as a result of an imported service from a .ts file

In my Jest test file with a .spec.js extension, I am importing an index.js file that I need to test. Here is the code snippet from the .spec.js file: var HttpService = require('./index.js').HttpService; The problem arises because the index.js f ...

Tips for sending API requests as an object rather than an array

Hello there! I'm having trouble posting the data as an object. I attempted to adjust the server code, but it keeps throwing errors. Here is a snippet of the server code: const projectData = []; /* Other server setup code */ // GET route app.get(&a ...

modifying output of data when onchange event is triggered

I am struggling with creating an onchange event for my option box in which the users of a site are listed. I have two input boxes designated for wins and losses, but the output is not changing when I select a user from the list. What could be wrong with my ...

Seeking assistance with managing Yarn workspaces

My current project involves working on a React Native application for a client. After I had already written a significant amount of code, my client requested a new feature to be added. This feature should have been simple to implement, but due to the compl ...

Get the page downloaded before displaying or animating the content

Is there a method to make a browser pause and wait for all the content of a page to finish downloading before displaying anything? My webpage has several CSS3 animations, but when it is first loaded, the animations appear choppy and distorted because the ...

Determine to which observable in the list the error corresponds

const obs1$ = this.service.getAllItems(); const obs2$ = this.service.getItemById(1); combineLatest([obs1$, obs2$]) .subscribe(pair => { const items = pair[0]; const item = pair[1]; // perform actions }, err => { // det ...

Utilizing objects from a JSON file within an HTML document

I'm currently in the process of creating a comprehensive to-do list, and I want to establish a JSON file that will link all the items on the list together. Despite my efforts, I find myself uncertain about the exact steps I need to take and the speci ...

Is it possible to dispatch actions from getters in Vuex?

Fiddle : here Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that t ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Using Laravel 8 to create connected dropdown menus with the power of Ajax

Struggling with setting up a dependent dropdown menu in Laravel 8 using Ajax. The first dropdown works fine, but the next two don't display any options. Being new to Laravel, I'm having trouble pinpointing the problem areas. Seeking assistance to ...

Upgrading email functionality: Combining PHP mail() with AJAX

My issue revolves around using the mail() function. When AJAX code is present, the email gets sent but without any message (the subject is intact though). However, when I remove the AJAX code, the email goes through without any problems. I'm not well ...

What Causes My Issue with $(document).ready()?

Currently delving into the world of jQuery, but I've hit a roadblock. Below is the snippet in question: var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.4.1.min.js'; script.type = " ...

How can I display a pattern using Javascript?

Can you help me create a JavaScript program using a for loop to print a pattern with n number of asterisks and numbers like this: 1 2 3\n 4 5 6 \n 7 8 9 ...

Using Webpack 4 and React Router, when trying to navigate to a sub path,

I'm currently working on setting up a router for my page, but I've encountered a problem. import * as React from 'react'; import {Route, Router, Switch, Redirect} from 'react-router-dom'; import { createBrowserHistory } from ...

Is it necessary to include a promise in the test when utilizing Chai as Promised?

Documentation provided by Chai as Promised indicates the following: Note: when using promise assertions, either return the promise or notify(done) must be used. Examples from the site demonstrate this concept: return doSomethingAsync().should.eventua ...

Dropping and dragging in the Dojo for the nested lists

Within my HTML code, I am using the Dojo drag and drop feature to sort attributes and move them to another section. However, I am having trouble figuring out how to sort the sections themselves. Here is the structure that I have created: <ul accept=" ...

The Invalid_grant OAuth2 error occurs when attempting to access the Google Drive API using

SOLVED! The issue was resolved by correcting the time on my Linux Server. Google's server was blocking access due to incorrect time settings. I used the following command on my Server to synchronize the time: ntpdate 0.europe.pool.ntp.org Original P ...

Tips for exporting/importing only a type definition in TypeScript:

Is it possible to export and import a type definition separately from the module in question? In Flowtype, achieving this can be done by having the file sub.js export the type myType with export type myType = {id: number};, and then in the file main.js, i ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...