【发布时间】:2021-12-05 13:23:48
【问题描述】:
我正在尝试使用功能组合通过 mixins 向对象添加行为:
const pipe = (...funcs: ((...args: any[]) => any)[]) => (initial: any) => funcs.reduce((object, fn) => fn(object), initial);
const speakMixin = <T,>(obj: T): T & { speak: () => void } => ({
...obj,
speak: () => console.log("I can speak!")
});
const flyMixin = <T,>(obj: T): T & { fly: () => void } => ({
...obj,
fly: () => console.log("i'm flying")
});
const chain = pipe(speakMixin, flyMixin);
const mixed = chain({});
mixed.fly(); // fly member is typed to any
有没有更好的方法来键入我的 pipe 函数,以便我在应用了 mixins 的对象上获得类型安全?
【问题讨论】:
-
这绝对是可能的,但它并不漂亮。您可以查看 lodash 流函数的类型以了解它是如何完成的。它类似于 Promise.all 的类型。
标签: typescript type-inference typescript-generics