import {Component} from 'react' import {isDev} from '../coding' export const STATE_OPERATION_HAVE_NOT_SET_UP_WARNING = [ '[StateOperation]: have not been set up with `comp` and `propName` yet', ].join('') export class StateOperation> { comp?: Component propName?: keyof State constructor(comp?: Component, propName?: keyof State) { if (comp && propName) { this.setup(comp, propName) } } private get hasBeenSetUp() { const hasSetUp = !!(this.comp && this.propName) if (!hasSetUp && isDev()) { throw new Error(STATE_OPERATION_HAVE_NOT_SET_UP_WARNING) } return hasSetUp } setup(comp: Component, propName: keyof State) { this.comp = comp this.propName = propName } get() { return ( this.hasBeenSetUp ? this.comp!.state[this.propName!] : undefined ) as unknown as V } set(value: V, callback?: () => void) { if (this.hasBeenSetUp) { this.comp!.setState( {[this.propName!]: value} as Record & State, callback ) } } }