What is the best way to retrieve the name of a static method within a class?

In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it.

I would like to be able to access the context by directly getting the method name, not only in a class static method but also in every other function.

Below is my attempt:

class CloudFunction {
  public static parse() {

    console.log(this.name); // CloudFunction
    console.log(CloudFunction.parse.name); // unable to retrieve anything here

    // Rather than declaring a `context` variable and assigning the method name to it.
    const context = 'parse';
    logger.debug('a log', { context, arguments: 'pubsubMessage' });

    //... many logs use this context

    // hoping for a better solution like:
    // const self = this;
    // logger.error(new Error('bad'), {context: self.name })
  }
}


CloudFunction.parse();

Unfortunately, none of these methods seem to work. Is there a way to use reflection to achieve this? I am uncertain if reflection can accomplish this task.

update

Here are my findings:

☁  DL-Toolkits [master] npx ts-node /Users/ldu020/workspace/github.com/mrdulin/ts-codelab/src/class/get-static-method-name/index.ts
CloudFunction

Answer №1

Am I correctly retrieving the method name, or is there a misunderstanding?

class ClassWithStaticMethod {
  static staticMethod() {
    console.log('1: ' + ClassWithStaticMethod.staticMethod.name); // output: '1: staticMethod'
    return ClassWithStaticMethod.staticMethod.name;
  }
}

console.log('2: ' + ClassWithStaticMethod.staticMethod()); // output: '2: staticMethod'

Sample code link

Answer №2

Perhaps the reason for this behavior could be attributed to the presence of the public access modifier preceding the static method.

class CloudFunction {
  static parse() {
    console.log(this.name); // CloudFunction
    console.log(CloudFunction.parse.name); // no output displayed

    const context = 'parse';
  }
}


CloudFunction.parse();

It is worth noting that this code functions correctly even without an access modifier specified.

Answer №3

Obtaining this information may not be as simple as it seems.

To tackle this issue, consider creating a new static variable that will store the current function name. Utilize decorators to update this variable whenever a function is called.

function changeContextName(target: object, propertyName: string, propertyDesciptor: PropertyDescriptor) {
  let method = propertyDesciptor.value;
  propertyDesciptor.value = function() {
    // let prevMethod = this.context; // backup previous method name
    this.context = propertyName;
    method.apply(this, arguments);
    // this.context = prevMethod; // restore previous method name
  };
}


class CloudFunction {
  public static context: string;

  @changeContextName
  public static parse() {

    console.log({context: this.context});
  }

  @changeContextName
  public test() {
    console.log({ context: CloudFunction.context});
  }
}

CloudFunction.parse();
(new CloudFunction()).test();

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

"Ensure that a directive is universally accessible throughout an angular2 final project by registering it

I have created a custom directive that I want to use throughout my application. How can I register my directives so they are accessible in the entire application? I have found outdated solutions for this issue and need a solution specific to Angular 2 fina ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

When trying to access a property in Typescript that may not exist on the object

Imagine having some data in JS like this example const obj = { // 'c' property should never be present a: 1, b: 2, } const keys = ['a', 'b', 'c'] // always contains 'a', 'b', or 'c' ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

tips for preventing issues when the data array is empty

Here is the JSON data that I am dealing with: { "id": 43, "dataEvento": "2022-09-01T00:00:00.000+0000", "dataInvio": null, "idComunicazioneAssociata": null, "certificatoMedico" ...

The element 'nz-list-item-meta-title' in NG-ZORRO is unrecognized

After installing NG-ZORRO for my project, I decided to start by incorporating their list component. However, I encountered errors with elements such as: 'nz-list-item-meta-title' and 'nz-list-item-action' not being recognized. I have e ...

"Canvas element's getContext method returning both WebGL2RenderingContext and RenderingContext - a conundrum for

Currently diving into typescript and facing a puzzling situation. I am attempting to check if the browser supports webgl. The detection process involves creating a canvas object on the document and obtaining the context to determine if it is "webgl" or "ex ...

Testing the submission event on a reactive form in Angular

Scenario In my component, I have a basic form implemented using reactive forms in Angular. My objective is to test the submission event of this form to ensure that the appropriate method is executed. The Issue at Hand I am encountering challenges in tri ...

Exploring the usage of intervalTimer with async and fakeAsync functions

In a particular section of the Angular Testing Guide, it discusses how to test components with asynchronous services, pointing out that: When writing test functions involving done rather than async and fakeAsync, it may be more cumbersome but remains a ...

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

Include the designated return type within a fat arrow function

No matter how hard I look, I cannot figure out the correct way to combine return type annotation with fat arrow syntax. class BasicCalculator{ value:number; constructor(value:number=0){ this.value=value; } add= (operand:number)=> ...

Ways to determine the number of duplicate items in an Array

I have an array of objects that contain part numbers, brand names, and supplier names. I need to find a concise and efficient way to determine the count of duplicate objects in the array. [ { partNum: 'ACDC1007', brandName: 'Electric&apo ...

Combining types: unable to utilize the second optional type within a for loop

I am facing an issue while looping through an array due to the union type. I am wondering what I have overlooked in the code below that is causing Visual Studio Code to not recognize the second optional type for that specific array. class Menu { // name ...

Utilizing props in styled components with Emotion-js and Typescript is not feasible

Check out this simple React component I created: import React, { ReactChild, ElementType } from 'react' import styled from '@emotion/styled' type WrapperPropsType = { size?: SizeType } type ButtonPropsType = { as?: ElementType< ...

Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false) const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') const [errorUsername, setErrorUsername] = React.useState(true) const [er ...

Using {angular} import from 'angular' is causing a malfunction in AngularJS version 1.5

React - 17.0 TypeScript - 4.1.2 Babel - 7.13.14 tsconfig.json { "compilerOptions": { "target": "es6", "module": "esnext", "moduleResolution": "node", "jsx": ...

The serverTimeStamp() function in firebase.firestore.FieldValue does not allow for the Timestamp data type to be used

async addNewUser(id: string, email: string) { await this.afs.doc<MemberProfileModel>(FirestoreDbConstant.MEMBER_PROFILES + `/${id}`).set({ email, registeredDate: firebase.firestore.FieldValue.serverTimestamp(), }); } This appro ...

Issue: Module not found; Typescript error encountered in a react application

I have a load_routes.js file in the node_express folder that is responsible for loading all the routes for my project. Everything was working smoothly until I decided to change the file extension from .js to .ts. Suddenly, I started encountering the follow ...