Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: how to get function name as string without TS2339 error

I found the following example in the Function.name documentation

const o = {
  foo(){}
};
o.foo.name; // "foo";

The problem in typescript (typed here):

    const o: { foo: () => void } = {
        foo: () => {
        }
    };
    o.foo.name;

comes when I want to retrieve o.foo.name, where I will get an error

TS2339 (property "name" does not exist)

How can I deal with it, keeping the object typing? I want to avoid having to cast the property "foo" like (<any>o.foo).name

PS: The use case is to keep the typing for further refactoring. For instance the following is safe to be refactored:

spyOn(o, (<any>o.foo).name)

While this one is not

spyOn(o, "foo")

PS 2: It seems retrieving function name could be problematic on ts: Get name of function in typescript

like image 250
Flavien Volken Avatar asked Jul 04 '26 08:07

Flavien Volken


1 Answers

The problem is that this code only works for newer versions of Javascript. If you change the target on the typescript compiler settings to es2015 the problem goes away. If you target es5 the definitions for that version do not include the name property because it might not work on older Javascript runtimes.

If you are ok with targeting es2015, that is ok, if not you should come up with a different solution that works for es5.

If you are targeting an environment that supports this property but you don't yet trust the es2015 implementation for all features, you could just add the the Function interface the missing property. At the top level in one of your files you can redefine the Function interface, and this will be merged into the default definition, adding the extra property:

interface Function {
  /**
   * Returns the name of the function. Function names are read-only and can not be changed.
   */
  readonly name: string;
}
like image 149
Titian Cernicova-Dragomir Avatar answered Jul 06 '26 13:07

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!