Home > Software design >  How to know what parameters a function expects
How to know what parameters a function expects

Time:12-03

I've a function like:

function myFunction(params) {
  // TODO: something
  console.log(params.message)
}

And I need to know all the keys that the myFunction function expects in the params object. Is this possible?

I've tried using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments but it didn't work

CodePudding user response:

toString will be helpful, but other than that you can't know. JavaScript doesn't store type information in runtime (TypeScript neither)

function myFunction(params) {
  // TODO: something
  console.log(params.message)
}

console.log(myFunction.toString())
console.log(eval)

CodePudding user response:

Nothing is built into the language that would help you here.

You have these choices:

  1. Find some documentation for this function and read it.
  2. Find the code for this function and see what properties it pays attention to or what comments in the code might help you.
  3. Find some other code that calls this function and see how it does the calling.

These are essentially your options. Read the doc or read code.

Javascript does not require any specification in the language of what properties are expected on an object passed into a function so there's nothing built into the language.

Fortunately, most things you use in the Javascript world are open source so you can usually go find the target code and just study it to see what it does.

If you made this a real world situation (rather than a hypothetical one) by providing the actual function you're calling and what module it's in, we could look at the best options for that specific situation and point you in a direction.

  • Related