Add a return type of string when a function is acc

2020-05-06 22:50发布

问题:

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 = () => {
  some logic..
  return bla
}

now when I use 'test()' I want the function executed. But when I use 'test' I want a custom string to be returned. Is it possible to achieve this via Object proxies somehow?

回答1:

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));



回答2:

You can do this if you first check the type of the variable, in particular you will check if its a Function:

function isFunc(functionToCheck) {
 return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
};

So if this is true, then your variable is infact a function and you can return the stuff you need from it:

const isItAFunction = somevariable;

if(isFunc(isItAFunction)) {
   // return your string
} else {
  // do something else
}