UNPKG

2.87 kBTypeScriptView Raw
1// Type definitions for prop-types 15.5
2// Project: https://github.com/reactjs/prop-types
3// Definitions by: DovydasNavickas <https://github.com/DovydasNavickas>
4// Ferdy Budhidharma <https://github.com/ferdaber>
5// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
6// TypeScript Version: 2.8
7
8import { ReactNode, ReactElement } from 'react';
9
10export const nominalTypeHack: unique symbol;
11
12export type IsOptional<T> = undefined | null extends T ? true : undefined extends T ? true : null extends T ? true : false;
13
14export type RequiredKeys<V> = { [K in keyof V]: V[K] extends Validator<infer T> ? IsOptional<T> extends true ? never : K : never }[keyof V];
15export type OptionalKeys<V> = Exclude<keyof V, RequiredKeys<V>>;
16export type InferPropsInner<V> = { [K in keyof V]: InferType<V[K]>; };
17
18export interface Validator<T> {
19 (props: object, propName: string, componentName: string, location: string, propFullName: string): Error | null;
20 [nominalTypeHack]?: T;
21}
22
23export interface Requireable<T> extends Validator<T | undefined | null> {
24 isRequired: Validator<NonNullable<T>>;
25}
26
27export type ValidationMap<T> = { [K in keyof T]-?: Validator<T[K]> };
28
29export type InferType<V> = V extends Validator<infer T> ? T : any;
30export type InferProps<V> =
31 & InferPropsInner<Pick<V, RequiredKeys<V>>>
32 & Partial<InferPropsInner<Pick<V, OptionalKeys<V>>>>;
33
34export const any: Requireable<any>;
35export const array: Requireable<any[]>;
36export const bool: Requireable<boolean>;
37export const func: Requireable<(...args: any[]) => any>;
38export const number: Requireable<number>;
39export const object: Requireable<object>;
40export const string: Requireable<string>;
41export const node: Requireable<ReactNode>;
42export const element: Requireable<ReactElement<any>>;
43export const symbol: Requireable<symbol>;
44export function instanceOf<T>(expectedClass: new (...args: any[]) => T): Requireable<T>;
45export function oneOf<T>(types: T[]): Requireable<T>;
46export function oneOfType<T extends Validator<any>>(types: T[]): Requireable<NonNullable<InferType<T>>>;
47export function arrayOf<T>(type: Validator<T>): Requireable<T[]>;
48export function objectOf<T>(type: Validator<T>): Requireable<{ [K in keyof any]: T; }>;
49export function shape<P extends ValidationMap<any>>(type: P): Requireable<InferProps<P>>;
50
51/**
52 * Assert that the values match with the type specs.
53 * Error messages are memorized and will only be shown once.
54 *
55 * @param typeSpecs Map of name to a ReactPropType
56 * @param values Runtime values that need to be type-checked
57 * @param location e.g. "prop", "context", "child context"
58 * @param componentName Name of the component for error messages.
59 * @param getStack Returns the component stack.
60 */
61export function checkPropTypes(typeSpecs: any, values: any, location: string, componentName: string, getStack?: () => any): void;