3

Is there a way in TypeScript to get all the methods in a Class that has a particular parameter?

I am trying to write a UnitTest around this.

For example

class Foo {
  constructor() { ... }
  set blah(b) { ... }
  get blah() { ... }
  method1(yes : any) { ... }
  method2(no : any) { ... }
  method3(yes : any) { ... }
  method4(no : any, not : any, this : any) { ... }
}

The idea should be get all the methods in Foo which has a single payload named 'yes'. Also i have a string form of the className.

So in this case it should an array of [method1, method3], in which i can loop against in my unit test.

This is what i got so far:

let className = 'Foo' // Assume that this is given
let methodNames = Object.getOwnPropertyNames(Object.getPrototypeOf(className))
methodNames.filter((x) => x !== <stuck here>).forEach((m) => { .. }

I don't want to do something like this. Curious if there was an easier way.

As well i have seen this page: How to get function parameter names/values dynamically?

But does not work in my case as my className is in a string formate.

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

let className = 'Foo' // Assume that this is given
let methodNames = Object.getPrototypeOf(className)
console.log(getParamNames(methodNames)) // Returns [Object, Object] also tried just className didn't work.
civic.sir
  • 400
  • 1
  • 9
  • 26
  • I haven't tried it, but I think with the typescript compiler API you would be able to retrieve the parameter names out of the AST tree. For instance, [here](https://ts-ast-viewer.com/#code/MYGwhgzhAEBiD29oG8BQ1rHgOwgFwCcBXYPeAgCgEoVoBfdaAWwFM8ALeAEwEYKBPFjABc0MNn41k9Rqw7cATBWxJR4ybQYY5nLgGYBQ6GolSZ2troAsy1WIkAaaCrzH7G6QzpA) you can inspect your code online and see that it parsed the parameter name. However, it doesn't seem like an "easier way" – A_A Oct 04 '20 at 07:21
  • Yeah this will work if i have the actually Class Object. Here i only have the className in string. Not sure how i'd do this. Also i tried the suggestion made above (about duplicate issue)- but will not work in my case since i'm dealing with string of the className not the actual class itself :( – civic.sir Oct 05 '20 at 01:03

0 Answers0