首页 > 解决方案 > 获取具有特定参数的对象的方法

问题描述

TypeScript 中有没有办法获取具有特定参数的类中的所有方法?

我正在尝试围绕此编写 UnitTest。

例如

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

这个想法应该是获取 Foo 中的所有方法,其中有一个名为“yes”的有效负载。我也有一个类名的字符串形式。

所以在这种情况下,它应该是一个数组[method1, method3],我可以在我的单元测试中循环。

这是我到目前为止得到的:

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

我不想做这样的事情。好奇是否有更简单的方法。

我也看过这个页面:如何动态获取函数参数名称/值?

但在我的情况下不起作用,因为我的 className 是字符串格式。

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.

标签: javascripttypescript

解决方案


推荐阅读