考虑:
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”吗?
答案 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')));