// Type definitions for React 16.4 // Project: http://facebook.github.io/react/ // Definitions by: Asana // AssureSign // Microsoft // John Reilly // Benoit Benezech // Patricio Zavolinsky // Digiguru // Eric Anderson // Albert Kurniawan // Tanguy Krotoff // Dovydas Navickas // Stéphane Goetz // Josh Rutherford // Guilherme Hübner // Ferdy Budhidharma // Johann Rakotoharisoa // Olivier Pascal // Martin Hochel // Frank Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// import * as CSS from 'csstype'; import * as PropTypes from 'prop-types'; type NativeAnimationEvent = AnimationEvent; type NativeClipboardEvent = ClipboardEvent; type NativeCompositionEvent = CompositionEvent; type NativeDragEvent = DragEvent; type NativeFocusEvent = FocusEvent; type NativeKeyboardEvent = KeyboardEvent; type NativeMouseEvent = MouseEvent; type NativeTouchEvent = TouchEvent; type NativePointerEvent = PointerEvent; type NativeTransitionEvent = TransitionEvent; type NativeUIEvent = UIEvent; type NativeWheelEvent = WheelEvent; // tslint:disable-next-line:export-just-namespace export = React; export as namespace React; declare namespace React { // // React Elements // ---------------------------------------------------------------------- type ReactType

= string | ComponentType

; type ComponentType

= ComponentClass

| StatelessComponent

; type Key = string | number; interface RefObject { readonly current: T | null; } type Ref = string | { bivarianceHack(instance: T | null): any }["bivarianceHack"] | RefObject; type ComponentState = any; interface Attributes { key?: Key; } interface ClassAttributes extends Attributes { ref?: Ref; } interface ReactElement

{ type: string | ComponentClass

| SFC

; props: P; key: Key | null; } interface SFCElement

extends ReactElement

{ type: SFC

; } type CElement> = ComponentElement; interface ComponentElement> extends ReactElement

{ type: ComponentClass

; ref?: Ref; } type ClassicElement

= CElement>; // string fallback for custom web-components interface DOMElement

| SVGAttributes, T extends Element> extends ReactElement

{ type: string; ref: Ref; } // ReactHTML for ReactHTMLElement // tslint:disable-next-line:no-empty-interface interface ReactHTMLElement extends DetailedReactHTMLElement, T> { } interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { type: keyof ReactHTML; } // ReactSVG for ReactSVGElement interface ReactSVGElement extends DOMElement, SVGElement> { type: keyof ReactSVG; } interface ReactPortal extends ReactElement { key: Key | null; children: ReactNode; } // // Factories // ---------------------------------------------------------------------- type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

; type SFCFactory

= (props?: Attributes & P, ...children: ReactNode[]) => SFCElement

; type ComponentFactory> = (props?: ClassAttributes & P, ...children: ReactNode[]) => CElement; type CFactory> = ComponentFactory; type ClassicFactory

= CFactory>; type DOMFactory

, T extends Element> = (props?: ClassAttributes & P | null, ...children: ReactNode[]) => DOMElement; // tslint:disable-next-line:no-empty-interface interface HTMLFactory extends DetailedHTMLFactory, T> {} interface DetailedHTMLFactory

, T extends HTMLElement> extends DOMFactory { (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; } interface SVGFactory extends DOMFactory, SVGElement> { (props?: ClassAttributes & SVGAttributes | null, ...children: ReactNode[]): ReactSVGElement; } // // React Nodes // http://facebook.github.io/react/docs/glossary.html // ---------------------------------------------------------------------- type ReactText = string | number; type ReactChild = ReactElement | ReactText; interface ReactNodeArray extends Array {} type ReactFragment = {} | ReactNodeArray; type ReactNode = ReactChild | ReactFragment | ReactPortal | string | number | boolean | null | undefined; // // Top Level API // ---------------------------------------------------------------------- // DOM Elements function createFactory( type: keyof ReactHTML): HTMLFactory; function createFactory( type: keyof ReactSVG): SVGFactory; function createFactory

, T extends Element>( type: string): DOMFactory; // Custom components function createFactory

(type: SFC

): SFCFactory

; function createFactory

( type: ClassType, ClassicComponentClass

>): CFactory>; function createFactory, C extends ComponentClass

>( type: ClassType): CFactory; function createFactory

(type: ComponentClass

): Factory

; // DOM Elements // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" function createElement( type: "input", props?: InputHTMLAttributes & ClassAttributes | null, ...children: ReactNode[]): DetailedReactHTMLElement, HTMLInputElement>; function createElement

, T extends HTMLElement>( type: keyof ReactHTML, props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; function createElement

, T extends SVGElement>( type: keyof ReactSVG, props?: ClassAttributes & P | null, ...children: ReactNode[]): ReactSVGElement; function createElement

, T extends Element>( type: string, props?: ClassAttributes & P | null, ...children: ReactNode[]): DOMElement; // Custom components function createElement

( type: SFC

, props?: Attributes & P | null, ...children: ReactNode[]): SFCElement

; function createElement

( type: ClassType, ClassicComponentClass

>, props?: ClassAttributes> & P | null, ...children: ReactNode[]): CElement>; function createElement, C extends ComponentClass

>( type: ClassType, props?: ClassAttributes & P | null, ...children: ReactNode[]): CElement; function createElement

( type: SFC

| ComponentClass

| string, props?: Attributes & P | null, ...children: ReactNode[]): ReactElement

; // DOM Elements // ReactHTMLElement function cloneElement

, T extends HTMLElement>( element: DetailedReactHTMLElement, props?: P, ...children: ReactNode[]): DetailedReactHTMLElement; // ReactHTMLElement, less specific function cloneElement

, T extends HTMLElement>( element: ReactHTMLElement, props?: P, ...children: ReactNode[]): ReactHTMLElement; // SVGElement function cloneElement

, T extends SVGElement>( element: ReactSVGElement, props?: P, ...children: ReactNode[]): ReactSVGElement; // DOM Element (has to be the last, because type checking stops at first overload that fits) function cloneElement

, T extends Element>( element: DOMElement, props?: DOMAttributes & P, ...children: ReactNode[]): DOMElement; // Custom components function cloneElement

( element: SFCElement

, props?: Partial

& Attributes, ...children: ReactNode[]): SFCElement

; function cloneElement>( element: CElement, props?: Partial

& ClassAttributes, ...children: ReactNode[]): CElement; function cloneElement

( element: ReactElement

, props?: Partial

& Attributes, ...children: ReactNode[]): ReactElement

; // Context via RenderProps interface ProviderProps { value: T; children?: ReactNode; } interface ConsumerProps { children: (value: T) => ReactNode; unstable_observedBits?: number; } type Provider = ComponentType>; type Consumer = ComponentType>; interface Context { Provider: Provider; Consumer: Consumer; } function createContext( defaultValue: T, calculateChangedBits?: (prev: T, next: T) => number ): Context; function isValidElement

(object: {} | null | undefined): object is ReactElement

; const Children: ReactChildren; const Fragment: ComponentType; const StrictMode: ComponentType; const version: string; // // Component API // ---------------------------------------------------------------------- type ReactInstance = Component | Element; // Base component for plain JS classes // tslint:disable-next-line:no-empty-interface interface Component

extends ComponentLifecycle { } class Component { constructor(props: Readonly

); /** * @deprecated * https://reactjs.org/docs/legacy-context.html */ constructor(props: P, context?: any); // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 // Also, the ` | S` allows intellisense to not be dumbisense setState( state: ((prevState: Readonly, props: Readonly

) => (Pick | S | null)) | (Pick | S | null), callback?: () => void ): void; forceUpdate(callBack?: () => void): void; render(): ReactNode; // React.Props is now deprecated, which means that the `children` // property is not available on `P` by default, even though you can // always pass children as variadic arguments to `createElement`. // In the future, if we can define its call signature conditionally // on the existence of `children` in `P`, then we should remove this. readonly props: Readonly<{ children?: ReactNode }> & Readonly

; state: Readonly; /** * @deprecated * https://reactjs.org/docs/legacy-context.html */ context: any; /** * @deprecated * https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs */ refs: { [key: string]: ReactInstance }; } class PureComponent

extends Component { } interface ClassicComponent

extends Component { replaceState(nextState: S, callback?: () => void): void; isMounted(): boolean; getInitialState?(): S; } interface ChildContextProvider { getChildContext(): CC; } // // Class Interfaces // ---------------------------------------------------------------------- type SFC

= StatelessComponent

; interface StatelessComponent

{ (props: P & { children?: ReactNode }, context?: any): ReactElement | null; propTypes?: ValidationMap

; contextTypes?: ValidationMap; defaultProps?: Partial

; displayName?: string; } interface RefForwardingComponent { (props: P & { children?: ReactNode }, ref?: Ref): ReactElement | null; propTypes?: ValidationMap

; contextTypes?: ValidationMap; defaultProps?: Partial

; displayName?: string; } interface ComponentClass

extends StaticLifecycle { new (props: P, context?: any): Component; propTypes?: ValidationMap

; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; defaultProps?: Partial

; displayName?: string; } interface ClassicComponentClass

extends ComponentClass

{ new (props: P, context?: any): ClassicComponent; getDefaultProps?(): P; } /** * We use an intersection type to infer multiple type parameters from * a single argument, which is useful for many top-level API defs. * See https://github.com/Microsoft/TypeScript/issues/7234 for more info. */ type ClassType, C extends ComponentClass

> = C & (new (props: P, context?: any) => T) & (new (props: P, context?: any) => { props: P }); // // Component Specs and Lifecycle // ---------------------------------------------------------------------- // This should actually be something like `Lifecycle | DeprecatedLifecycle`, // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle // methods are present. interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { /** * Called immediately after a component is mounted. Setting state here will trigger re-rendering. */ componentDidMount?(): void; /** * Called to determine whether the change in props and state should trigger a re-render. * * `Component` always returns true. * `PureComponent` implements a shallow comparison on props and state and returns true if any * props or states have changed. * * If false is returned, `Component#render`, `componentWillUpdate` * and `componentDidUpdate` will not be called. */ shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; /** * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. */ componentWillUnmount?(): void; /** * Catches exceptions generated in descendant components. Unhandled exceptions will cause * the entire component tree to unmount. */ componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; } // Unfortunately, we have no way of declaring that the component constructor must implement this interface StaticLifecycle { getDerivedStateFromProps?: GetDerivedStateFromProps; } type GetDerivedStateFromProps = /** * Returns an update to a component's state based on its new props and old state. * * Note: its presence prevents any of the deprecated lifecycle methods from being invoked */ (nextProps: Readonly

, prevState: S) => Partial | null; // This should be "infer SS" but can't use it yet interface NewLifecycle { /** * Runs before React applies the result of `render` to the document, and * returns an object to be given to componentDidUpdate. Useful for saving * things such as scroll position before `render` causes changes to it. * * Note: the presence of getSnapshotBeforeUpdate prevents any of the deprecated * lifecycle events from running. */ getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; /** * Called immediately after updating occurs. Not called for the initial render. * * The snapshot is only present if getSnapshotBeforeUpdate is present and returns non-null. */ componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; } interface DeprecatedLifecycle { /** * Called immediately before mounting occurs, and before `Component#render`. * Avoid introducing any side-effects or subscriptions in this method. * * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps * prevents this from being invoked. * * @deprecated 16.3, use componentDidMount or the constructor instead; will stop working in React 17 * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path */ componentWillMount?(): void; /** * Called immediately before mounting occurs, and before `Component#render`. * Avoid introducing any side-effects or subscriptions in this method. * * This method will not stop working in React 17. * * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps * prevents this from being invoked. * * @deprecated 16.3, use componentDidMount or the constructor instead * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path */ UNSAFE_componentWillMount?(): void; /** * Called when the component may be receiving new props. * React may call this even if props have not changed, so be sure to compare new and existing * props if you only want to handle changes. * * Calling `Component#setState` generally does not trigger this method. * * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps * prevents this from being invoked. * * @deprecated 16.3, use static getDerivedStateFromProps instead; will stop working in React 17 * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path */ componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; /** * Called when the component may be receiving new props. * React may call this even if props have not changed, so be sure to compare new and existing * props if you only want to handle changes. * * Calling `Component#setState` generally does not trigger this method. * * This method will not stop working in React 17. * * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps * prevents this from being invoked. * * @deprecated 16.3, use static getDerivedStateFromProps instead * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path */ UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; /** * Called immediately before rendering when new props or state is received. Not called for the initial render. * * Note: You cannot call `Component#setState` here. * * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps * prevents this from being invoked. * * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path */ componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; /** * Called immediately before rendering when new props or state is received. Not called for the initial render. * * Note: You cannot call `Component#setState` here. * * This method will not stop working in React 17. * * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps * prevents this from being invoked. * * @deprecated 16.3, use getSnapshotBeforeUpdate instead * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path */ UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; } interface Mixin extends ComponentLifecycle { mixins?: Array>; statics?: { [key: string]: any; }; displayName?: string; propTypes?: ValidationMap; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; getDefaultProps?(): P; getInitialState?(): S; } interface ComponentSpec extends Mixin { render(): ReactNode; [propertyName: string]: any; } function createRef(): RefObject; function forwardRef(Component: RefForwardingComponent): ComponentType

>; // // Event System // ---------------------------------------------------------------------- interface SyntheticEvent { bubbles: boolean; /** * A reference to the element on which the event listener is registered. */ currentTarget: EventTarget & T; cancelable: boolean; defaultPrevented: boolean; eventPhase: number; isTrusted: boolean; nativeEvent: Event; preventDefault(): void; isDefaultPrevented(): boolean; stopPropagation(): void; isPropagationStopped(): boolean; persist(): void; // If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 /** * A reference to the element from which the event was originally dispatched. * This might be a child element to the element on which the event listener is registered. * * @see currentTarget */ target: EventTarget; timeStamp: number; type: string; } interface ClipboardEvent extends SyntheticEvent { clipboardData: DataTransfer; nativeEvent: NativeClipboardEvent; } interface CompositionEvent extends SyntheticEvent { data: string; nativeEvent: NativeCompositionEvent; } interface DragEvent extends MouseEvent { dataTransfer: DataTransfer; nativeEvent: NativeDragEvent; } interface PointerEvent extends MouseEvent { pointerId: number; pressure: number; tiltX: number; tiltY: number; width: number; height: number; pointerType: 'mouse' | 'pen' | 'touch'; isPrimary: boolean; nativeEvent: NativePointerEvent; } interface FocusEvent extends SyntheticEvent { nativeEvent: NativeFocusEvent; relatedTarget: EventTarget; target: EventTarget & T; } // tslint:disable-next-line:no-empty-interface interface FormEvent extends SyntheticEvent { } interface InvalidEvent extends SyntheticEvent { target: EventTarget & T; } interface ChangeEvent extends SyntheticEvent { target: EventTarget & T; } interface KeyboardEvent extends SyntheticEvent { altKey: boolean; charCode: number; ctrlKey: boolean; /** * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. */ getModifierState(key: string): boolean; /** * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values */ key: string; keyCode: number; locale: string; location: number; metaKey: boolean; nativeEvent: NativeKeyboardEvent; repeat: boolean; shiftKey: boolean; which: number; } interface MouseEvent extends SyntheticEvent { altKey: boolean; button: number; buttons: number; clientX: number; clientY: number; ctrlKey: boolean; /** * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. */ getModifierState(key: string): boolean; metaKey: boolean; nativeEvent: NativeMouseEvent; pageX: number; pageY: number; relatedTarget: EventTarget; screenX: number; screenY: number; shiftKey: boolean; } interface TouchEvent extends SyntheticEvent { altKey: boolean; changedTouches: TouchList; ctrlKey: boolean; /** * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. */ getModifierState(key: string): boolean; metaKey: boolean; nativeEvent: NativeTouchEvent; shiftKey: boolean; targetTouches: TouchList; touches: TouchList; } interface UIEvent extends SyntheticEvent { detail: number; nativeEvent: NativeUIEvent; view: AbstractView; } interface WheelEvent extends MouseEvent { deltaMode: number; deltaX: number; deltaY: number; deltaZ: number; nativeEvent: NativeWheelEvent; } interface AnimationEvent extends SyntheticEvent { animationName: string; elapsedTime: number; nativeEvent: NativeAnimationEvent; pseudoElement: string; } interface TransitionEvent extends SyntheticEvent { elapsedTime: number; nativeEvent: NativeTransitionEvent; propertyName: string; pseudoElement: string; } // // Event Handler Types // ---------------------------------------------------------------------- type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; type ReactEventHandler = EventHandler>; type ClipboardEventHandler = EventHandler>; type CompositionEventHandler = EventHandler>; type DragEventHandler = EventHandler>; type FocusEventHandler = EventHandler>; type FormEventHandler = EventHandler>; type ChangeEventHandler = EventHandler>; type KeyboardEventHandler = EventHandler>; type MouseEventHandler = EventHandler>; type TouchEventHandler = EventHandler>; type PointerEventHandler = EventHandler>; type UIEventHandler = EventHandler>; type WheelEventHandler = EventHandler>; type AnimationEventHandler = EventHandler>; type TransitionEventHandler = EventHandler>; // // Props / DOM Attributes // ---------------------------------------------------------------------- /** * @deprecated. This was used to allow clients to pass `ref` and `key` * to `createElement`, which is no longer necessary due to intersection * types. If you need to declare a props object before passing it to * `createElement` or a factory, use `ClassAttributes`: * * ```ts * var b: Button | null; * var props: ButtonProps & ClassAttributes