Add a return type of string when a function is accessed like a variable

后端 未结 2 750
甜味超标
甜味超标 2021-01-27 14:26

I am not sure if this is possible (in fact I\'m struggling to work out what to google for) but here it goes:

I have a function

const test = () => {
           


        
2条回答
  •  迷失自我
    2021-01-27 15:19

    Is it possible to achieve this via Object proxies somehow?

    No, this is not possible. You cannot make a callable proxy as a primitive string. If you want your test (function) object to show a custom string when stringified (like when concatenated to an other string), just give it a custom .toString() method:

    const test = Object.assign(() => "Hello World", {
      toString() {
        return "123";
      }
    });
    console.log("Example call " + test());
    console.log("Example stringification " + test);
    console.log("Function object", test);
    console.log("as a string", String(test));

提交回复
热议问题