context.d.ts 1.6 KB

1234567891011121314151617181920212223242526
  1. import * as React from 'react';
  2. export type Selector<ContextProps, SelectorValue = ContextProps> = (value: ContextProps) => SelectorValue;
  3. export type Trigger<ContextProps> = (value: ContextProps) => void;
  4. export type Listeners<ContextProps> = Set<Trigger<ContextProps>>;
  5. export interface Context<ContextProps> {
  6. getValue: () => ContextProps;
  7. listeners: Listeners<ContextProps>;
  8. }
  9. export interface ContextSelectorProviderProps<T> {
  10. value: T;
  11. children?: React.ReactNode;
  12. }
  13. export interface SelectorContext<ContextProps> {
  14. Context: React.Context<Context<ContextProps>>;
  15. Provider: React.ComponentType<ContextSelectorProviderProps<ContextProps>>;
  16. defaultValue?: ContextProps;
  17. }
  18. export declare function createContext<ContextProps>(defaultValue?: ContextProps): SelectorContext<ContextProps>;
  19. /** e.g. useSelect(userContext) => user */
  20. export declare function useContext<ContextProps>(holder: SelectorContext<ContextProps>): ContextProps;
  21. /** e.g. useSelect(userContext, user => user.name) => user.name */
  22. export declare function useContext<ContextProps, SelectorValue>(holder: SelectorContext<ContextProps>, selector: Selector<ContextProps, SelectorValue>): SelectorValue;
  23. /** e.g. useSelect(userContext, ['name', 'age']) => user { name, age } */
  24. export declare function useContext<ContextProps, SelectorValue extends Partial<ContextProps>>(holder: SelectorContext<ContextProps>, selector: (keyof ContextProps)[]): SelectorValue;
  25. /** e.g. useSelect(userContext, 'name') => user.name */
  26. export declare function useContext<ContextProps, PropName extends keyof ContextProps>(holder: SelectorContext<ContextProps>, selector: PropName): ContextProps[PropName];