typescript 打字稿功能性混合物实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 打字稿功能性混合物实例相关的知识,希望对你有一定的参考价值。
interface MyMixedObject<T> {
setIntercept: (value: number) => MyMixedObject<T> & T;
setSlope: (value: number) => MyMixedObject<T> & T;
y: (x: number) => number;
}
const myFunctionalMixin = (
{ slope = 2, intercept = 1 } = { slope: 2, intercept: 1 },
) => <T extends object>(o: T): MyMixedObject<T> & T => {
let myIntercept = intercept;
let mySlope = slope;
return Object.assign({}, o, {
setIntercept(value: number): MyMixedObject<T> & T {
myIntercept = value;
return this;
},
setSlope(value: number): MyMixedObject<T> & T {
mySlope = value;
return this;
},
y(x: number): number {
return x * mySlope + myIntercept;
},
});
};
const objectA = {
eat() {
console.log('Eat an apple');
},
};
const objectB = {
drink() {
console.log('Drink a beverage');
},
};
const myFunctionalMixinObjectA = myFunctionalMixin()(objectA);
myFunctionalMixinObjectA.eat(); // Eat an apple
console.log(myFunctionalMixinObjectA.y(1)); // (1 * 2) + 1 = 3
console.log(myFunctionalMixinObjectA.y(2)); // (2 * 2) + 1 = 5
myFunctionalMixinObjectA.setIntercept(3).setSlope(4);
console.log(myFunctionalMixinObjectA.y(1)); // (1 * 4) + 3 = 7
console.log(myFunctionalMixinObjectA.y(2)); // (2 * 4) + 3 = 11
const myFunctionalMixinObjectB = myFunctionalMixin({ slope: 3, intercept: 2 })(objectB);
myFunctionalMixinObjectB.drink(); // Drink a beverage
console.log(myFunctionalMixinObjectB.y(1)); // (1 * 3) + 2 = 5;
console.log(myFunctionalMixinObjectB.y(2)); // (2 * 3) + 2 = 8;
myFunctionalMixinObjectB.setIntercept(3).setSlope(4);
console.log(myFunctionalMixinObjectB.y(1)); // (1 * 4) + 3 = 7
console.log(myFunctionalMixinObjectB.y(2)); // (2 * 4) + 3 = 11
以上是关于typescript 打字稿功能性混合物实例的主要内容,如果未能解决你的问题,请参考以下文章
typescript 打字稿备忘单 - 语法功能和示例
如何从打字稿访问文档实例
为自定义打字稿错误实例实施 instanceof 检查?
如何将实例变量传递给打字稿装饰器参数?
打字稿中的多个构造函数
用值实例化打字稿类实例(对象初始化)