Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of static method in a class?

Tags:

typescript

I print many logs in the static method and I want to use the method name as context. But I don't want to declare a context variable and assign the function/method name to it.

I want to use the context by accessing the method name. Not only in a class static method, but also in every function.

Here is my try:

class CloudFunction {
  public static parse() {

    console.log(this.name); // CloudFunction
    console.log(CloudFunction.parse.name); // get nothing here


    // Don't want to declare `context` variable and assign method name to it.
    const context = 'parse';
    logger.debug('a log', { context, arguments: 'pubsubMessage' });

    //... many logs use this context

    // want the better way like this:
    // const self = this;
    // logger.error(new Error('bad'), {context: self.name })
  }
}


CloudFunction.parse();

None of them work. Can I use reflect way to get it? I am not sure reflect can do this.

update

Here is my result:

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

like image 499
slideshowp2 Avatar asked Sep 01 '25 01:09

slideshowp2


1 Answers

I am getting the name of the method, or do I misunderstand anything?

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'

Code sample

like image 110
Jonathan Stellwag Avatar answered Sep 02 '25 14:09

Jonathan Stellwag