UNPKG

@react-querybuilder/core

Version:

React Query Builder component for constructing queries and filters, with utilities for executing them in various database and evaluation contexts

1,257 lines (1,070 loc) 45.3 kB
//#region ../../node_modules/type-fest/source/union-to-intersection.d.ts /** Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153). @example ``` import type {UnionToIntersection} from 'type-fest'; type Union = {the(): void} | {great(arg: string): void} | {escape: boolean}; type Intersection = UnionToIntersection<Union>; //=> {the(): void; great(arg: string): void; escape: boolean}; ``` A more applicable example which could make its way into your library code follows. @example ``` import type {UnionToIntersection} from 'type-fest'; class CommandOne { commands: { a1: () => undefined, b1: () => undefined, } } class CommandTwo { commands: { a2: (argA: string) => undefined, b2: (argB: string) => undefined, } } const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands); type Union = typeof union; //=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void} type Intersection = UnionToIntersection<Union>; //=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void} ``` @category Type */ type UnionToIntersection<Union> = ( // `extends unknown` is always going to be the case and is used to convert the // `Union` into a [distributive conditional // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). Union extends unknown // The union type is used as the only argument to a function since the union // of function arguments is an intersection. ? (distributedUnion: Union) => void // This won't happen. : never // Infer the `Intersection` type since TypeScript represents the positional // arguments of unions of functions as an intersection of the union. ) extends ((mergedIntersection: infer Intersection) => void) // The `& Union` is to ensure result of `UnionToIntersection<A | B>` is always assignable to `A | B` ? Intersection & Union : never; //#endregion //#region ../../node_modules/type-fest/source/keys-of-union.d.ts /** Create a union of all keys from a given type, even those exclusive to specific union members. Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member. @link https://stackoverflow.com/a/49402091 @example ``` import type {KeysOfUnion} from 'type-fest'; type A = { common: string; a: number; }; type B = { common: string; b: string; }; type C = { common: string; c: boolean; }; type Union = A | B | C; type CommonKeys = keyof Union; //=> 'common' type AllKeys = KeysOfUnion<Union>; //=> 'common' | 'a' | 'b' | 'c' ``` @category Object */ type KeysOfUnion<ObjectType> = // Hack to fix https://github.com/sindresorhus/type-fest/issues/1008 keyof UnionToIntersection<ObjectType extends unknown ? Record<keyof ObjectType, never> : never>; //#endregion //#region ../../node_modules/type-fest/source/is-any.d.ts /** Returns a boolean for whether the given type is `any`. @link https://stackoverflow.com/a/49928360/1490091 Useful in type utilities, such as disallowing `any`s to be passed to a function. @example ``` import type {IsAny} from 'type-fest'; const typedObject = {a: 1, b: 2} as const; const anyObject: any = {a: 1, b: 2}; function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) { return obj[key]; } const typedA = get(typedObject, 'a'); //=> 1 const anyA = get(anyObject, 'a'); //=> any ``` @category Type Guard @category Utilities */ type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false; //#endregion //#region ../../node_modules/type-fest/source/is-optional-key-of.d.ts /** Returns a boolean for whether the given key is an optional key of type. This is useful when writing utility types or schema validators that need to differentiate `optional` keys. @example ``` import type {IsOptionalKeyOf} from 'type-fest'; interface User { name: string; surname: string; luckyNumber?: number; } interface Admin { name: string; surname?: string; } type T1 = IsOptionalKeyOf<User, 'luckyNumber'>; //=> true type T2 = IsOptionalKeyOf<User, 'name'>; //=> false type T3 = IsOptionalKeyOf<User, 'name' | 'luckyNumber'>; //=> boolean type T4 = IsOptionalKeyOf<User | Admin, 'name'>; //=> false type T5 = IsOptionalKeyOf<User | Admin, 'surname'>; //=> boolean ``` @category Type Guard @category Utilities */ type IsOptionalKeyOf<Type extends object, Key$1 extends keyof Type> = IsAny<Type | Key$1> extends true ? never : Key$1 extends keyof Type ? Type extends Record<Key$1, Type[Key$1]> ? false : true : false; //#endregion //#region ../../node_modules/type-fest/source/optional-keys-of.d.ts /** Extract all optional keys from the given type. This is useful when you want to create a new type that contains different type values for the optional keys only. @example ``` import type {OptionalKeysOf, Except} from 'type-fest'; interface User { name: string; surname: string; luckyNumber?: number; } const REMOVE_FIELD = Symbol('remove field symbol'); type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & { [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD; }; const update1: UpdateOperation<User> = { name: 'Alice' }; const update2: UpdateOperation<User> = { name: 'Bob', luckyNumber: REMOVE_FIELD }; ``` @category Utilities */ type OptionalKeysOf<Type extends object> = Type extends unknown // For distributing `Type` ? (keyof { [Key in keyof Type as IsOptionalKeyOf<Type, Key> extends false ? never : Key]: never }) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf<Type>` is always assignable to `keyof Type` : never; //#endregion //#region ../../node_modules/type-fest/source/required-keys-of.d.ts /** Extract all required keys from the given type. This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc... @example ``` import type {RequiredKeysOf} from 'type-fest'; declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn; interface User { name: string; surname: string; luckyNumber?: number; } const validator1 = createValidation<User>('name', value => value.length < 25); const validator2 = createValidation<User>('surname', value => value.length < 25); ``` @category Utilities */ type RequiredKeysOf<Type extends object> = Type extends unknown // For distributing `Type` ? Exclude<keyof Type, OptionalKeysOf<Type>> : never; //#endregion //#region ../../node_modules/type-fest/source/is-never.d.ts /** Returns a boolean for whether the given type is `never`. @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919 @link https://stackoverflow.com/a/53984913/10292952 @link https://www.zhenghao.io/posts/ts-never Useful in type utilities, such as checking if something does not occur. @example ``` import type {IsNever, And} from 'type-fest'; // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts type AreStringsEqual<A extends string, B extends string> = And< IsNever<Exclude<A, B>> extends true ? true : false, IsNever<Exclude<B, A>> extends true ? true : false >; type EndIfEqual<I extends string, O extends string> = AreStringsEqual<I, O> extends true ? never : void; function endIfEqual<I extends string, O extends string>(input: I, output: O): EndIfEqual<I, O> { if (input === output) { process.exit(0); } } endIfEqual('abc', 'abc'); //=> never endIfEqual('abc', '123'); //=> void ``` @category Type Guard @category Utilities */ type IsNever<T> = [T] extends [never] ? true : false; //#endregion //#region ../../node_modules/type-fest/source/if.d.ts /** An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`. Use-cases: - You can use this in combination with `Is*` types to create an if-else-like experience. For example, `If<IsAny<any>, 'is any', 'not any'>`. Note: - Returns a union of if branch and else branch if the given type is `boolean` or `any`. For example, `If<boolean, 'Y', 'N'>` will return `'Y' | 'N'`. - Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`. @example ``` import {If} from 'type-fest'; type A = If<true, 'yes', 'no'>; //=> 'yes' type B = If<false, 'yes', 'no'>; //=> 'no' type C = If<boolean, 'yes', 'no'>; //=> 'yes' | 'no' type D = If<any, 'yes', 'no'>; //=> 'yes' | 'no' type E = If<never, 'yes', 'no'>; //=> 'no' ``` @example ``` import {If, IsAny, IsNever} from 'type-fest'; type A = If<IsAny<unknown>, 'is any', 'not any'>; //=> 'not any' type B = If<IsNever<never>, 'is never', 'not never'>; //=> 'is never' ``` @example ``` import {If, IsEqual} from 'type-fest'; type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>; type A = IfEqual<string, string, 'equal', 'not equal'>; //=> 'equal' type B = IfEqual<string, number, 'equal', 'not equal'>; //=> 'not equal' ``` @category Type Guard @category Utilities */ type If<Type extends boolean, IfBranch, ElseBranch> = IsNever<Type> extends true ? ElseBranch : Type extends true ? IfBranch : ElseBranch; //#endregion //#region ../../node_modules/type-fest/source/unknown-array.d.ts /** Represents an array with `unknown` value. Use case: You want a type that all arrays can be assigned to, but you don't care about the value. @example ``` import type {UnknownArray} from 'type-fest'; type IsArray<T> = T extends UnknownArray ? true : false; type A = IsArray<['foo']>; //=> true type B = IsArray<readonly number[]>; //=> true type C = IsArray<string>; //=> false ``` @category Type @category Array */ type UnknownArray = readonly unknown[]; //#endregion //#region ../../node_modules/type-fest/source/internal/array.d.ts /** Returns whether the given array `T` is readonly. */ type IsArrayReadonly<T extends UnknownArray> = If<IsNever<T>, false, T extends unknown[] ? false : true>; //#endregion //#region ../../node_modules/type-fest/source/simplify.d.ts /** Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability. @example ``` import type {Simplify} from 'type-fest'; type PositionProps = { top: number; left: number; }; type SizeProps = { width: number; height: number; }; // In your editor, hovering over `Props` will show a flattened object with all the properties. type Props = Simplify<PositionProps & SizeProps>; ``` Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface. If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`. @example ``` import type {Simplify} from 'type-fest'; interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } type SomeType = { foo: number; bar?: string; baz: number | undefined; }; const literal = {foo: 123, bar: 'hello', baz: 456}; const someType: SomeType = literal; const someInterface: SomeInterface = literal; function fn(object: Record<string, unknown>): void {} fn(literal); // Good: literal object type is sealed fn(someType); // Good: type is sealed fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type` ``` @link https://github.com/microsoft/TypeScript/issues/15300 @see SimplifyDeep @category Object */ type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}; //#endregion //#region ../../node_modules/type-fest/source/is-equal.d.ts /** Returns a boolean for whether the two given types are equal. @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650 @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796 Use-cases: - If you want to make a conditional branch based on the result of a comparison of two types. @example ``` import type {IsEqual} from 'type-fest'; // This type returns a boolean for whether the given array includes the given item. // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal. type Includes<Value extends readonly any[], Item> = Value extends readonly [Value[0], ...infer rest] ? IsEqual<Value[0], Item> extends true ? true : Includes<rest, Item> : false; ``` @category Type Guard @category Utilities */ type IsEqual<A, B> = [A, B] extends [infer AA, infer BB] ? [AA] extends [never] ? [BB] extends [never] ? true : false : [BB] extends [never] ? false : _IsEqual<AA, BB> : false; // This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`. type _IsEqual<A, B> = (<G>() => G extends A & G | G ? 1 : 2) extends (<G>() => G extends B & G | G ? 1 : 2) ? true : false; //#endregion //#region ../../node_modules/type-fest/source/omit-index-signature.d.ts /** Omit any index signatures from the given object type, leaving only explicitly defined properties. This is the counterpart of `PickIndexSignature`. Use-cases: - Remove overly permissive signatures from third-party types. This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747). It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`. (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.) ``` const indexed: Record<string, unknown> = {}; // Allowed const keyed: Record<'foo', unknown> = {}; // Error // => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar ``` Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another: ``` type Indexed = {} extends Record<string, unknown> ? '✅ `{}` is assignable to `Record<string, unknown>`' : '❌ `{}` is NOT assignable to `Record<string, unknown>`'; // => '✅ `{}` is assignable to `Record<string, unknown>`' type Keyed = {} extends Record<'foo' | 'bar', unknown> ? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`" : "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"; // => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`" ``` Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`... ``` import type {OmitIndexSignature} from 'type-fest'; type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType // Map each key of `ObjectType`... ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`. }; ``` ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)... ``` import type {OmitIndexSignature} from 'type-fest'; type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType // Is `{}` assignable to `Record<KeyType, unknown>`? as {} extends Record<KeyType, unknown> ? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>` : ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>` ]: ObjectType[KeyType]; }; ``` If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it. @example ``` import type {OmitIndexSignature} from 'type-fest'; interface Example { // These index signatures will be removed. [x: string]: any [x: number]: any [x: symbol]: any [x: `head-${string}`]: string [x: `${string}-tail`]: string [x: `head-${string}-tail`]: string [x: `${bigint}`]: string [x: `embedded-${number}`]: string // These explicitly defined keys will remain. foo: 'bar'; qux?: 'baz'; } type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>; // => { foo: 'bar'; qux?: 'baz' | undefined; } ``` @see PickIndexSignature @category Object */ type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? never : KeyType]: ObjectType[KeyType] }; //#endregion //#region ../../node_modules/type-fest/source/pick-index-signature.d.ts /** Pick only index signatures from the given object type, leaving out all explicitly defined properties. This is the counterpart of `OmitIndexSignature`. @example ``` import type {PickIndexSignature} from 'type-fest'; declare const symbolKey: unique symbol; type Example = { // These index signatures will remain. [x: string]: unknown; [x: number]: unknown; [x: symbol]: unknown; [x: `head-${string}`]: string; [x: `${string}-tail`]: string; [x: `head-${string}-tail`]: string; [x: `${bigint}`]: string; [x: `embedded-${number}`]: string; // These explicitly defined keys will be removed. ['kebab-case-key']: string; [symbolKey]: string; foo: 'bar'; qux?: 'baz'; }; type ExampleIndexSignature = PickIndexSignature<Example>; // { // [x: string]: unknown; // [x: number]: unknown; // [x: symbol]: unknown; // [x: `head-${string}`]: string; // [x: `${string}-tail`]: string; // [x: `head-${string}-tail`]: string; // [x: `${bigint}`]: string; // [x: `embedded-${number}`]: string; // } ``` @see OmitIndexSignature @category Object */ type PickIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? KeyType : never]: ObjectType[KeyType] }; //#endregion //#region ../../node_modules/type-fest/source/merge.d.ts // Merges two objects without worrying about index signatures. type SimpleMerge<Destination, Source> = { [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key] } & Source; /** Merge two types into a new type. Keys of the second type overrides keys of the first type. @example ``` import type {Merge} from 'type-fest'; interface Foo { [x: string]: unknown; [x: number]: unknown; foo: string; bar: symbol; } type Bar = { [x: number]: number; [x: symbol]: unknown; bar: Date; baz: boolean; }; export type FooBar = Merge<Foo, Bar>; // => { // [x: string]: unknown; // [x: number]: number; // [x: symbol]: unknown; // foo: string; // bar: Date; // baz: boolean; // } ``` @category Object */ type Merge<Destination, Source> = Simplify<SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>> & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>>; //#endregion //#region ../../node_modules/type-fest/source/internal/object.d.ts /** Works similar to the built-in `Pick` utility type, except for the following differences: - Distributes over union types and allows picking keys from any member of the union type. - Primitives types are returned as-is. - Picks all keys if `Keys` is `any`. - Doesn't pick `number` from a `string` index signature. @example ``` type ImageUpload = { url: string; size: number; thumbnailUrl: string; }; type VideoUpload = { url: string; duration: number; encodingFormat: string; }; // Distributes over union types and allows picking keys from any member of the union type type MediaDisplay = HomomorphicPick<ImageUpload | VideoUpload, "url" | "size" | "duration">; //=> {url: string; size: number} | {url: string; duration: number} // Primitive types are returned as-is type Primitive = HomomorphicPick<string | number, 'toUpperCase' | 'toString'>; //=> string | number // Picks all keys if `Keys` is `any` type Any = HomomorphicPick<{a: 1; b: 2} | {c: 3}, any>; //=> {a: 1; b: 2} | {c: 3} // Doesn't pick `number` from a `string` index signature type IndexSignature = HomomorphicPick<{[k: string]: unknown}, number>; //=> {} */ type HomomorphicPick<T, Keys extends KeysOfUnion<T>> = { [P in keyof T as Extract<P, Keys>]: T[P] }; /** Merges user specified options with default options. @example ``` type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false}; type SpecifiedOptions = {leavesOnly: true}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; //=> {maxRecursionDepth: 10; leavesOnly: true} ``` @example ``` // Complains if default values are not provided for optional options type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10}; type SpecifiedOptions = {}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; // ~~~~~~~~~~~~~~~~~~~ // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'. ``` @example ``` // Complains if an option's default type does not conform to the expected type type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'}; type SpecifiedOptions = {}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; // ~~~~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` @example ``` // Complains if an option's specified type does not conform to the expected type type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false}; type SpecifiedOptions = {leavesOnly: 'yes'}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; // ~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` */ type ApplyDefaultOptions<Options extends object, Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>, SpecifiedOptions extends Options> = If<IsAny<SpecifiedOptions>, Defaults, If<IsNever<SpecifiedOptions>, Defaults, Simplify<Merge<Defaults, { [Key in keyof SpecifiedOptions as Key extends OptionalKeysOf<Options> ? undefined extends SpecifiedOptions[Key] ? never : Key : Key]: SpecifiedOptions[Key] }> & Required<Options>>>>; //#endregion //#region ../../node_modules/type-fest/source/except.d.ts /** Filter out keys from an object. Returns `never` if `Exclude` is strictly equal to `Key`. Returns `never` if `Key` extends `Exclude`. Returns `Key` otherwise. @example ``` type Filtered = Filter<'foo', 'foo'>; //=> never ``` @example ``` type Filtered = Filter<'bar', string>; //=> never ``` @example ``` type Filtered = Filter<'bar', 'foo'>; //=> 'bar' ``` @see {Except} */ type Filter<KeyType$1, ExcludeType> = IsEqual<KeyType$1, ExcludeType> extends true ? never : (KeyType$1 extends ExcludeType ? never : KeyType$1); type ExceptOptions = { /** Disallow assigning non-specified properties. Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`. @default false */ requireExactProps?: boolean; }; type DefaultExceptOptions = { requireExactProps: false; }; /** Create a type from an object type without certain keys. We recommend setting the `requireExactProps` option to `true`. This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically. This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)). @example ``` import type {Except} from 'type-fest'; type Foo = { a: number; b: string; }; type FooWithoutA = Except<Foo, 'a'>; //=> {b: string} const fooWithoutA: FooWithoutA = {a: 1, b: '2'}; //=> errors: 'a' does not exist in type '{ b: string; }' type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>; //=> {a: number} & Partial<Record<"b", never>> const fooWithoutB: FooWithoutB = {a: 1, b: '2'}; //=> errors at 'b': Type 'string' is not assignable to type 'undefined'. // The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures. // Consider the following example: type UserData = { [metadata: string]: string; email: string; name: string; role: 'admin' | 'user'; }; // `Omit` clearly doesn't behave as expected in this case: type PostPayload = Omit<UserData, 'email'>; //=> type PostPayload = { [x: string]: string; [x: number]: string; } // In situations like this, `Except` works better. // It simply removes the `email` key while preserving all the other keys. type PostPayload = Except<UserData, 'email'>; //=> type PostPayload = { [x: string]: string; name: string; role: 'admin' | 'user'; } ``` @category Object */ type Except<ObjectType, KeysType extends keyof ObjectType, Options extends ExceptOptions = {}> = _Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>; type _Except<ObjectType, KeysType extends keyof ObjectType, Options extends Required<ExceptOptions>> = { [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType] } & (Options['requireExactProps'] extends true ? Partial<Record<KeysType, never>> : {}); //#endregion //#region ../../node_modules/type-fest/source/set-required.d.ts /** Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type. Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required. @example ``` import type {SetRequired} from 'type-fest'; type Foo = { a?: number; b: string; c?: boolean; } type SomeRequired = SetRequired<Foo, 'b' | 'c'>; // type SomeRequired = { // a?: number; // b: string; // Was already required and still is. // c: boolean; // Is now required. // } // Set specific indices in an array to be required. type ArrayExample = SetRequired<[number?, number?, number?], 0 | 1>; //=> [number, number, number?] ``` @category Object */ type SetRequired<BaseType, Keys extends keyof BaseType> = (BaseType extends ((...arguments_: never) => any) ? (...arguments_: Parameters<BaseType>) => ReturnType<BaseType> : unknown) & _SetRequired<BaseType, Keys>; type _SetRequired<BaseType, Keys extends keyof BaseType> = BaseType extends UnknownArray ? SetArrayRequired<BaseType, Keys> extends infer ResultantArray ? If<IsArrayReadonly<BaseType>, Readonly<ResultantArray>, ResultantArray> : never : Simplify< // Pick just the keys that are optional from the base type. Except<BaseType, Keys> & // Pick the keys that should be required from the base type and make them required. Required<HomomorphicPick<BaseType, Keys>>>; /** Remove the optional modifier from the specified keys in an array. */ type SetArrayRequired<TArray extends UnknownArray, Keys, Counter extends any[] = [], Accumulator extends UnknownArray = []> = TArray extends unknown // For distributing `TArray` when it's a union ? keyof TArray & `${number}` extends never // Exit if `TArray` is empty (e.g., []), or // `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`). ? [...Accumulator, ...TArray] : TArray extends readonly [(infer First)?, ...infer Rest] ? '0' extends OptionalKeysOf<TArray> // If the first element of `TArray` is optional ? `${Counter['length']}` extends `${Keys & (string | number)}` // If the current index needs to be required ? SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, First]> // If the current element is optional, but it doesn't need to be required, // then we can exit early, since no further elements can now be made required. : [...Accumulator, ...TArray] : SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, TArray[0]]> : never // Should never happen, since `[(infer F)?, ...infer R]` is a top-type for arrays. : never; // Should never happen //#endregion //#region src/types/options.d.ts type RequireAtLeastOne<ObjectType, KeysType extends keyof ObjectType> = { [Key in KeysType]-?: Required<Pick<ObjectType, Key>> & Partial<Pick<ObjectType, Exclude<KeysType, Key>>> }[KeysType] & Except<ObjectType, KeysType>; /** * Adds an `unknown` index property to an interface. */ type WithUnknownIndex<T> = T & { [key: string]: unknown; }; /** * Do not use this type directly; use {@link Option}, {@link ValueOption}, * or {@link FullOption} instead. For specific option types, you can use * {@link FullField}, {@link FullOperator}, or {@link FullCombinator}, * all of which extend {@link FullOption}. * * @group Option Lists */ interface BaseOption<N extends string = string> { name?: N; value?: N; label: string; disabled?: boolean; } /** * A generic option. Used directly in {@link OptionList} or * as the child element of an {@link OptionGroup}. * * @group Option Lists */ type Option<N extends string = string> = Simplify<WithUnknownIndex<SetRequired<BaseOption<N>, "name">>>; /** * A generic {@link Option} with either a `name` or `value` as its primary identifier. * {@link OptionList}-type props on the {@link react-querybuilder!QueryBuilder QueryBuilder} component accept this type, * but corresponding props passed down to subcomponents will always be augmented * to {@link FullOption} first. * * @group Option Lists */ type FlexibleOption<N extends string = string> = Simplify<WithUnknownIndex<RequireAtLeastOne<BaseOption<N>, "name" | "value">>>; /** * Utility type to turn an {@link Option}, {@link ValueOption}, or {@link BaseOption} * into a {@link FlexibleOption}. * * @group Option Lists */ type ToFlexibleOption<Opt$1 extends BaseOption | string> = WithUnknownIndex<RequireAtLeastOne<Opt$1 extends string ? FlexibleOption<Opt$1> : Opt$1, "name" | "value">>; /** * A generic {@link Option} requiring both `name` _and_ `value` properties. * Props that extend {@link OptionList} accept {@link BaseOption}, but * corresponding props sent to subcomponents will always be augmented to this * type first to ensure both `name` and `value` are available. * * NOTE: Do not extend from this type directly. Use {@link BaseFullOption} * (optionally wrapped in {@link WithUnknownIndex}) instead, otherwise * the `unknown` index property will cause issues. See {@link Option} and * {@link ValueOption} for examples. * * @group Option Lists */ type FullOption<N extends string = string> = Simplify<WithUnknownIndex<SetRequired<BaseOption<N>, "name" | "value">>>; /** * This type is identical to {@link FullOption} but without the `unknown` index * property. Extend from this type instead of {@link FullOption} directly. * * @group Option Lists */ type BaseFullOption<N extends string = string> = Simplify<SetRequired<BaseOption<N>, "name" | "value">>; /** * Utility type to turn an {@link Option}, {@link ValueOption} or * {@link BaseOption} into a {@link FullOption}. * * @group Option Lists */ type ToFullOption<Opt$1 extends BaseOption> = Opt$1 extends BaseFullOption ? Opt$1 : Opt$1 extends BaseOption<infer IdentifierType> ? WithUnknownIndex<Opt$1 & FullOption<IdentifierType>> : never; /** * A group of {@link Option}s, usually within an {@link OptionList}. * * @group Option Lists */ interface OptionGroup<Opt$1 extends BaseOption = FlexibleOption> { label: string; options: WithUnknownIndex<Opt$1>[]; } /** * A group of {@link BaseOption}s, usually within a {@link FlexibleOptionList}. * * @group Option Lists */ type FlexibleOptionGroup<Opt$1 extends BaseOption | string = BaseOption> = { label: string; options: (Opt$1 extends BaseFullOption ? Opt$1 : ToFlexibleOption<Opt$1>)[]; }; /** * Either an array of {@link Option}s or an array of {@link OptionGroup}s. * * @group Option Lists */ type OptionList<Opt$1 extends Option = Option> = Opt$1[] | OptionGroup<Opt$1>[]; /** * An array of options or option groups, like {@link OptionList} but the option type * may use either `name` or `value` as the primary identifier. * * @group Option Lists */ type FlexibleOptionList<Opt$1 extends BaseOption> = ToFlexibleOption<Opt$1>[] | FlexibleOptionGroup<ToFlexibleOption<Opt$1>>[]; /** * An array of options or option groups, like {@link OptionList}, but using * {@link FullOption} instead of {@link Option}. This means that every member is * guaranteed to have both `name` and `value`. * * @group Option Lists */ type FullOptionList<Opt$1 extends BaseOption> = Opt$1 extends BaseFullOption ? Opt$1[] | OptionGroup<Opt$1>[] : ToFullOption<Opt$1>[] | OptionGroup<ToFullOption<Opt$1>>[]; //#endregion //#region src/types/ruleGroups.d.ts /** * Properties common to both rules and groups. */ interface CommonRuleAndGroupProperties { path?: Path; id?: string; disabled?: boolean; /** * Whether this rule or group is muted. When muted, the rule or group * is excluded from query export formats (SQL, JSON, MongoDB, etc.). * For groups, muting recursively mutes all children. */ muted?: boolean; } /** * The main rule type. The `field`, `operator`, and `value` properties * can be narrowed with generics. */ interface RuleType<F extends string = string, O extends string = string, V$1 = any, C extends string = string> extends CommonRuleAndGroupProperties { field: F; operator: O; value: V$1; valueSource?: ValueSource; match?: MatchConfig; /** * Only used when adding a rule to a query that uses independent combinators. */ combinatorPreceding?: C; } /** * The main rule group type. This type is used for query definitions as well as * all sub-groups of queries. */ interface RuleGroupType<R extends RuleType = RuleType, C extends string = string> extends CommonRuleAndGroupProperties { combinator: C; rules: RuleGroupArray<RuleGroupType<R, C>, R>; not?: boolean; } /** * The type of the `rules` array in a {@link RuleGroupType}. */ type RuleGroupArray<RG extends RuleGroupType = RuleGroupType, R extends RuleType = RuleType> = (R | RG)[]; /** * The type of the `rules` array in a {@link DefaultRuleGroupType}. */ type DefaultRuleGroupArray<F extends string = string> = RuleGroupArray<DefaultRuleGroupType, DefaultRuleType<F>>; /** * {@link RuleGroupType} with the `combinator` property limited to * {@link DefaultCombinatorNameExtended} and `rules` limited to {@link DefaultRuleType}. */ type DefaultRuleGroupType<F extends string = string> = RuleGroupType<DefaultRuleType<F>, DefaultCombinatorNameExtended> & { rules: DefaultRuleGroupArray<F>; }; /** * {@link RuleType} with the `operator` property limited to {@link DefaultOperatorName}. */ type DefaultRuleType<F extends string = string> = RuleType<F, DefaultOperatorName>; /** * Default allowed values for the `combinator` property. * * @group Option Lists */ type DefaultCombinatorName = "and" | "or"; /** * Default allowed values for the `combinator` property, plus `"xor"`. * * @group Option Lists */ type DefaultCombinatorNameExtended = DefaultCombinatorName | "xor"; /** * Default values for the `operator` property. * * @group Option Lists */ type DefaultOperatorName = "=" | "!=" | "<" | ">" | "<=" | ">=" | "contains" | "beginsWith" | "endsWith" | "doesNotContain" | "doesNotBeginWith" | "doesNotEndWith" | "null" | "notNull" | "in" | "notIn" | "between" | "notBetween"; //#endregion //#region src/types/ruleGroupsIC.utils.d.ts type MAXIMUM_ALLOWED_BOUNDARY = 80; type MappedTuple<Tuple extends Array<unknown>, Result extends Array<unknown> = [], Count extends ReadonlyArray<number> = []> = Count["length"] extends MAXIMUM_ALLOWED_BOUNDARY ? Result : Tuple extends [] ? [] : Result extends [] ? MappedTuple<Tuple, Tuple, [...Count, 1]> : MappedTuple<Tuple, Result | [...Result, ...Tuple], [...Count, 1]>; //#endregion //#region src/types/ruleGroupsIC.d.ts /** * The main rule group interface when using independent combinators. This type is used * for query definitions as well as all sub-groups of queries. */ interface RuleGroupTypeIC<R extends RuleType = RuleType, C extends string = string> extends Except<RuleGroupType<R, C>, "combinator" | "rules"> { combinator?: undefined; rules: RuleGroupICArray<RuleGroupTypeIC<R, C>, R, C>; /** * Only used when adding a rule to a query that uses independent combinators */ combinatorPreceding?: C; } /** * Shorthand for "either {@link RuleGroupType} or {@link RuleGroupTypeIC}". */ type RuleGroupTypeAny<R extends RuleType = RuleType, C extends string = string> = RuleGroupType<R, C> | RuleGroupTypeIC<R, C>; /** * The type of the `rules` array in a {@link RuleGroupTypeIC}. */ type RuleGroupICArray<RG extends RuleGroupTypeIC = RuleGroupTypeIC, R extends RuleType = RuleType, C extends string = string> = [R | RG] | [R | RG, ...MappedTuple<[C, R | RG]>] | ((R | RG)[] & { length: 0; }); /** * The type of the `rules` array in a {@link DefaultRuleGroupTypeIC}. */ type DefaultRuleGroupICArray<F extends string = string> = RuleGroupICArray<DefaultRuleGroupTypeIC<F>, DefaultRuleType<F>, DefaultCombinatorName>; /** * {@link RuleGroupTypeIC} with combinators limited to * {@link DefaultCombinatorName} and rules limited to {@link DefaultRuleType}. */ interface DefaultRuleGroupTypeIC<F extends string = string> extends RuleGroupTypeIC<DefaultRuleType<F>> { rules: DefaultRuleGroupICArray<F>; } //#endregion //#region src/types/validation.d.ts /** * Object with a `valid` boolean value and optional `reasons`. */ interface ValidationResult { valid: boolean; reasons?: any[]; } /** * Map of rule/group `id` to its respective {@link ValidationResult}. */ type ValidationMap = Record<string, boolean | ValidationResult>; /** * Function that validates a query. */ type QueryValidator = (query: RuleGroupTypeAny) => boolean | ValidationMap; /** * Function that validates a rule. */ type RuleValidator = (rule: RuleType) => boolean | ValidationResult; //#endregion //#region src/types/basic.d.ts /** * @see https://react-querybuilder.js.org/docs/tips/path */ type Path = number[]; /** * String of classnames, array of classname strings, or object where the * keys are classnames and those with truthy values will be included. * Suitable for passing to the `clsx` package. */ type Classname = string | string[] | Record<string, any>; /** * A source for the `value` property of a rule. */ type ValueSource = "value" | "field"; /** * Type of {@link react-querybuilder!ValueEditor ValueEditor} that will be displayed. */ type ValueEditorType = "text" | "select" | "checkbox" | "radio" | "textarea" | "switch" | "multiselect" | null; /** * A valid array of potential value sources. * * @see {@link ValueSource} */ type ValueSources = ["value"] | ["value", "field"] | ["field", "value"] | ["field"]; type ValueSourceFlexibleOptions = ToFlexibleOptionArrays<ValueSources>; type ToFlexibleOptionArrays<Sources extends readonly string[]> = Sources extends unknown ? { [K in keyof Sources]: FlexibleOption<Sources[K]> } : never; type WithOptionalClassName<T> = T & { className?: Classname; }; /** * HTML5 input types */ type InputType = "button" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "image" | "month" | "number" | "password" | "radio" | "range" | "reset" | "search" | "submit" | "tel" | "text" | "time" | "url" | "week" | "bigint" | (string & {}); /** * Quantification mode describing how many elements of the value array must pass * the filter for the rule itself to pass. * * For "atLeast", "atMost", and "exactly", the threshold value will be converted to * a percentage if the number is less than 1. Non-numeric values and numbers less * than 0 will be ignored. */ interface MatchConfig { mode: MatchMode; threshold?: number | null | undefined; } type MatchMode = "all" | "some" | "none" | "atLeast" | "atMost" | "exactly"; /** * Base for all Field types/interfaces. */ interface BaseFullField<FieldName extends string = string, OperatorName extends string = string, ValueName extends string = string, OperatorObj extends FullOption = FullOption<OperatorName>, ValueObj extends FullOption = FullOption<ValueName>> extends WithOptionalClassName<BaseFullOption<FieldName>> { id?: string; operators?: FlexibleOptionList<OperatorObj> | OperatorName[] | FlexibleOption<OperatorName>[] | (OperatorName | FlexibleOption<OperatorName>)[]; valueEditorType?: ValueEditorType | ((operator: OperatorName) => ValueEditorType); valueSources?: ValueSources | ValueSourceFlexibleOptions | ((operator: OperatorName) => ValueSources | ValueSourceFlexibleOptions); inputType?: InputType | null; values?: FlexibleOptionList<ValueObj>; matchModes?: boolean | MatchMode[] | FlexibleOption<MatchMode>[]; /** Properties of items in the value. */ subproperties?: FlexibleOptionList<FullField>; defaultOperator?: OperatorName; defaultValue?: any; placeholder?: string; validator?: RuleValidator; comparator?: string | ((f: FullField, operator: string) => boolean); } /** * Full field definition used in the `fields` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. * This type requires both `name` and `value`, but the `fields` prop itself * can use a {@link FlexibleOption} where only one of `name` or `value` is * required (along with `label`), or {@link Field} where only `name` and * `label` are required. * * The `name`/`value`, `operators`, and `values` properties of this interface * can be narrowed with generics. * * @group Option Lists */ type FullField<FieldName extends string = string, OperatorName extends string = string, ValueName extends string = string, OperatorObj extends FullOption = FullOption<OperatorName>, ValueObj extends FullOption = FullOption<ValueName>> = Simplify<FullOption<FieldName> & BaseFullField<FieldName, OperatorName, ValueName, OperatorObj, ValueObj>>; /** * Allowed values of the {@link FullOperator} property `arity`. A value of `"unary"` or * a number less than two will cause the default {@link react-querybuilder!ValueEditor ValueEditor} to render `null`. */ type Arity = number | "unary" | "binary" | "ternary"; /** * Full operator definition used in the `operators`/`getOperators` props of * {@link react-querybuilder!QueryBuilder QueryBuilder}. This type requires both `name` and `value`, but the * `operators`/`getOperators` props themselves can use a {@link FlexibleOption} * where only one of `name` or `value` is required, or {@link FullOperator} where * only `name` is required. * * The `name`/`value` properties of this interface can be narrowed with generics. * * @group Option Lists */ interface FullOperator<N extends string = string> extends WithOptionalClassName<FullOption<N>> { arity?: Arity; } type ParseNumberMethodName = "enhanced" | "native" | "strict"; /** * Parsing algorithms used by {@link parseNumber}. */ type ParseNumbersModerationLevel = "-limited" | ""; /** * Options for the `parseNumbers` prop of {@link react-querybuilder!QueryBuilder QueryBuilder}. */ type ParseNumbersPropConfig = boolean | `${ParseNumberMethodName}${ParseNumbersModerationLevel}`; //#endregion export { Except as C, SetRequired as S, RuleGroupType as _, ValueSource as a, FullOptionList as b, RuleValidator as c, DefaultRuleGroupTypeIC as d, RuleGroupTypeAny as f, DefaultRuleGroupType as g, DefaultOperatorName as h, ParseNumbersPropConfig as i, ValidationMap as l, DefaultCombinatorName as m, FullOperator as n, ValueSources as o, RuleGroupTypeIC as p, InputType as r, QueryValidator as s, FullField as t, ValidationResult as u, RuleType as v, OptionList as x, FlexibleOptionList as y }; //# sourceMappingURL=basic-BeKPP0_1.d.ts.map