修改成员变量的方法如何支持函数式?

我希望构建一个类似于useState的函数。


class template {
    count:number

    ModifyCount(func:(_count:number)=>number){
        this.count = func(this.count)
    }

    ModifyCount2(_count:number){
        this.count = _count
    }

    ModifyCount3<T>(func: T | (_count:T)=>T ){
        //...
    }
}

希望把ModifyCountModifyCount2合并为一个同一个函数
不知道该如何实现?

阅读 1.5k
1 个回答

请问是想实现这种吗?

class template {
    count: number;

    constructor() {
        this.count = 0;
    }

    ModifyCount(value: (_count: number) => number): void;
    ModifyCount(value: number): void;
    ModifyCount(value: any) {
        if (typeof value === 'number') {
            this.count = value;
        } else if (typeof value === 'function') {
            this.count = value(this.count);
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题