返回一个返回成员变量的函数的函数

时间:2018-09-28 08:33:03

标签: javascript typescript functional-programming prototype

考虑:

const compose = <S, T, R>(func1: (inp2: T) => R, func2: (inp: S) => T): (inp: S) => R => ((arg: S) => func1(func2(arg)));
const not = (val: boolean): boolean => !val;
const equals = <T>(val1: T): (val2: T) => boolean => ((val2: T): boolean => (val1 == val2));

和班级

class MyClass {
  constructor(public readonly name: string) { }
}

以下是在列表myarray中搜索名称为MyClass的{​​{1}}的两种方法:

(1)使用搜索

"find me"

(2)将myarray.filter(compose(equals("find me"), (c: MyClass): string => c.name)); 添加到类定义中,然后使用

进行搜索
public getName(): string {return this.name; }

问题:这两个选项都很详细。可以定义一个接受一个类和一个成员变量的函子,并为此成员变量返回一个“ getter”吗?

1 个答案:

答案 0 :(得分:1)

我们可以使用keyof以类型安全的方式构建这样的函数:

const get = <T, K extends keyof T>(cls: new (...a: any[]) => T, key: K) => (c: T) => c[key];
var found = myarray.some(compose(equals("find me"), get(MyClass, 'name')));

进一步的简化将是创建一个类专用的getter构建器函数。可以将其作为静态成员或单独变量保留在类中,具体取决于您希望如何在代码中拆分关注点:

const getBuilder = <T>(cls: new (...a: any[]) => T) => <K extends keyof T>(key: K) => (c: T) => c[key];
class MyClass {
  constructor(public readonly name: string) { }
  static get = getBuilder(MyClass); // getter builder on class
}
let myarray: MyClass[] = []
const myClassGet = getBuilder(MyClass);// class dedicated builder 
var found = myarray.some(compose(equals("find me"), myClassGet('name')));
var found2 = myarray.some(compose(equals("find me"), MyClass.get('name')));