import { Component , ReactNode } from 'react' ; type Props = { onToggle : ( on : boolean ) => void ; children : ( api : API ) => ReactNode ; } ; type API = ReturnType < Toggle [ 'getApi' ] > ; type State = Readonly < typeof initialState > ; const initialState = { on : false } ; export class Toggle extends Component < Props , State > { readonly state = initialState ; private toggle = ( ) => this . setState ( ( { on } ) => ( { on : ! on } ) , ( ) => this . props . onToggle ( this . state . on ) ) ; private getApi ( ) { return { on : this . state . on , toggle : this . toggle , } ; } render ( ) { const { children } = this . props ; if ( ! isFunction ( children ) ) { throw new Error ( 'children is mandatory and needs to be a function!' ) ; } return children ( this . getApi ( ) ) ; } } const isFunction = < T extends Function > ( value ) : value is T => typeof value === 'function' ;