muratgozel
muratgozel

Reputation: 2589

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

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?

Upvotes: 4

Views: 662

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075039

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

Upvotes: 9

Related Questions