2 回答
TA贡献1777条经验 获得超10个赞
function ext<T, E>(obj: T, extension: E) {
return (receiver: (extended: T & E) => any) => {
receiver(new Proxy(obj, {
get(target, prop, receiver) {
if(prop in extension)
return extension[prop];
return Reflect.get(...arguments);
},
// TODO has, set, etc. according to needs
} as T & E));
};
}
ext(a, { includesAnyOf })(a => {
a.includesAnyOf("stuff");
});
任务完成。
function ext(obj, extension) {
return (receiver) => {
receiver(new Proxy(obj, {
get(target, prop, receiver) {
if(prop in extension)
return extension[prop];
return Reflect.get(...arguments);
},
// TODO has, set, etc. according to needs
}));
};
}
function includesAnyOf(...searchElements) {
return searchElements.some(_ => this.includes(_));
}
const a = [1, 2, 3];
ext(a, { includesAnyOf })(a => {
console.log(a.includesAnyOf("stuff"));
});
你能想到更好的方法吗?
老实说,我没有看到比常规功能有任何好处。在 C# 和其他语言中,它很有用,因为您可以使用自动完成功能轻松找到这些扩展。无论您如何在 TS 中执行此操作,都无法达到该目的。
TA贡献1887条经验 获得超5个赞
我发现这样做的最简单方法是使用lodash.partial进行currying。
function includesAnyOf<T>(array: T[], ...searchElements: T[]) {
return searchElements.some(_ => array.includes(_));
}
import { partial } from 'lodash';
const a = [1, 2, 3];
const b = 3;
const ext = (o) => {
return {
includesAnyOf: partial(includesAnyOf, o)
};
};
console.log(
ext(a).includesAnyOf(b) // true
);
添加回答
举报