I'm in the process of creating functional mixins using TypeScript. Below is the code I have written so far:
const flying = (o: object) => {
let isFlying = false;
return Object.assign({}, o, {
fly() {
isFlying = true;
return this;
},
isFlying: () => isFlying,
land() {
isFlying = false;
return this;
}
});
};
const quacking = (quack: string) => (o: object) =>
Object.assign({}, o, {
quack: () => quack
});
const createDuck = (quack: string) => flying(quacking(quack)({}));
const duck = createDuck('Quack!');
duck.isFlying(); // TypeScript approves! ✅
duck.quack(); // TypeScript says there is no `quack` method! 🚫
The issue I am facing is that TypeScript does not recognize that the duck can also quack. How can I make TypeScript understand the functionalities added by the previous mixins?
(I suspect the problem lies in o: object
... Perhaps it needs to deduce the type of the argument while ensuring it is an object for Object.assign
to function correctly. Another approach could involve utilizing the spread operator
{ ...o, ...{ /* ... flying or quacking ... */ } }
.)