Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There A Way To Know Function's Type Of Return Value Without Executing It?

Tags:

javascript

I have an array of functions inside an object. One returns an object and the other one returns string:

{
  id: 'test-1',
  children: [
    function childOne() {
      return {
        id: 'child-1'
      }
    },
    function childTwo() {
      return 'text.'
    }
  ]
}

Is there a way to detect type of a return value without executing functions?

like image 734
muratgozel Avatar asked Oct 19 '25 05:10

muratgozel


1 Answers

Not in JavaScript, no, because:

  • Declaring a return type isn't a JavaScript concept.
  • Even if you used a parser to parse the function's source, functions can return different types depending on their inputs, the state they close over, the time you happen to look, or even at random.

TypeScript adds a layer of static type checking to JavaScript, if this is something that you regularly find you need. But even then, that information is erased at runtime, so if you need this information at runtime, TypeScript won't help.

Instead, you'll need to include that as information in the array, for instance:

{
  id: 'test-1',
  children: [
    {
      returns: "object",
      fn: function childOne() {
        return {
          id: 'child-1'
        };
      }
    },
    {
      returns: "string",
      fn: function childTwo() {
        return 'text.';
      }
    }
  ]
}

Or, since functions are objects:

{
  id: 'test-1',
  children: [
    addReturns("object", function childOne() {
      return {
        id: 'child-1'
      }
    }),
    addReturns("string", function childTwo() {
      return 'text.'
    })
  ]
}

...where addReturns is:

function addReturns(type, fn) {
  fn.returns = type;
  return fn;
}
like image 131
T.J. Crowder Avatar answered Oct 21 '25 19:10

T.J. Crowder



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!