我有下面的代码来自Enum,它为每个值创建enum +功能。
我想摆脱这2个“ typeof”是否可行?
const TEST = createEnumComparator<typeof Test, SuperCompareEnums<typeof Test>>(Test, SuperCompareEnums);
这就是我想要得到的并做同样的事情
const TEST = createEnumComparator<Test, SuperCompareEnums<Test>>(Test, SuperCompareEnums);
或者类似的东西将是最好的
const TEST = createEnumComparator<SuperCompareEnums<Test>>(Test, SuperCompareEnums);
整个代码
class CompareEnums<T> {
constructor(protected value: keyof T) {
}
public is(value: keyof T) {
return value === this.value;
}
}
class SuperCompareEnums<T> extends CompareEnums<T> {
sayHello() {
console.log('hello ' + this.value);
}
}
interface Constructor<T> {
new(...args: any[]): T;
}
function createEnumComparator<TObj1, TObj2 extends CompareEnums<TObj1>>(obj1: TObj1, obj2: Constructor<TObj2>): EnumAsComparator<TObj1, TObj2> {
return _.mapValues<any>(obj1, value => new obj2(value)) as any;
}
// --------------------------------------------
enum Test {
A = 'A',
B = 'B'
}
const TEST = createEnumComparator<typeof Test, SuperCompareEnums<typeof Test>>(Test, SuperCompareEnums);
// --------------------------------------------
console.warn(1111111111111);
console.warn(TEST.A.is(Test.A), 1);
console.warn(TEST.B.is(Test.B));
console.warn(TEST.B.sayHello());
console.warn(TEST.A.is(Test.B));
// --------------------------------------------
type EnumAsComparator<TObj1, TObj2> = {
[P in keyof TObj1]: TObj2;
};