/** * Returns an array of indices where the predicate function returns true for the corresponding element in the input array. * @param input - The array to search. * @param predicate - The function to test each element of the array. * @returns An array of indices where the predicate function returns true. */ declare function arrFindIndices(input: Array, predicate: (value: T) => boolean): number[]; /** * Get array element at index or create it using factory function if it doesn't exist. */ declare function arrGetOrDefault(array: V[], index: number, factory: (index: number) => V): V; /** * Checks if an array has any duplicate elements. * @param arr - The array to check for duplicates. * @returns A boolean indicating whether the array has duplicates. * @typeParam T - The type of elements in the array. */ declare function arrHasDuplicates(arr: T[]): boolean; /** * Returns all indexes at which an element is found. * @param input The array to search * @template T - The type of elements in the input array. * @returns An array of indices where the specified element can be found. * @param element The element to find * @example ```ts * const inputArray = [1, 2, 3, 2, 4, 2, 5]; * const elementToFind = 2; * arrIndicesOf(inputArray, elementToFind); * //=> [1, 3, 5] * ``` */ declare function arrIndicesOf(input: Array, element: T): number[]; /** * This function takes an array and a callback function as arguments. It applies the callback function to each element of the array, mutating the original array in the process. * @template T The type of elements in the input array. * @param input The array to be mapped over. * @param f The callback function to be applied to each element of the array. This function takes three arguments: the current element, its index, and the original array. * @returns The original array, mutated by the callback function. * @example ```ts * arrMapMutable([1, 2, 3], (value: number) => value * 2); * //=> [2, 4, 6] * ``` */ declare function arrMapMutable(input: Array, f: (value: T, index: number, array: T[]) => T): Array; /** Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). @category Type */ type Primitive = | null | undefined | string | number | boolean | symbol | bigint; /** 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; //=> {the(): void} & {great(arg: string): void} & {escape: boolean} ``` @category Type */ type UnionToIntersection = ( // `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` is always assignable to `A | B` ? Intersection & Union : never; /** 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; //=> 'common' | 'a' | 'b' | 'c' ``` @category Object */ type KeysOfUnion = // Hack to fix https://github.com/sindresorhus/type-fest/issues/1008 keyof UnionToIntersection : never>; /** 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 extends true ? {} : Record), K extends keyof O = keyof O>(object: O, key: K) { return object[key]; } const typedA = get(typedObject, 'a'); //=> 1 const anyA = get(anyObject, 'a'); //=> any ``` @category Type Guard @category Utilities */ type IsAny = 0 extends 1 & NoInfer ? true : false; /** 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'; type User = { name: string; surname: string; luckyNumber?: number; }; type Admin = { name: string; surname?: string; }; type T1 = IsOptionalKeyOf; //=> true type T2 = IsOptionalKeyOf; //=> false type T3 = IsOptionalKeyOf; //=> boolean type T4 = IsOptionalKeyOf; //=> false type T5 = IsOptionalKeyOf; //=> boolean ``` @category Type Guard @category Utilities */ type IsOptionalKeyOf = IsAny extends true ? never : Key extends keyof Type ? Type extends Record ? false : true : false; /** 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'; type User = { name: string; surname: string; luckyNumber?: number; }; const REMOVE_FIELD = Symbol('remove field symbol'); type UpdateOperation = Except, OptionalKeysOf> & { [Key in OptionalKeysOf]?: Entity[Key] | typeof REMOVE_FIELD; }; const update1: UpdateOperation = { name: 'Alice', }; const update2: UpdateOperation = { name: 'Bob', luckyNumber: REMOVE_FIELD, }; ``` @category Utilities */ type OptionalKeysOf = Type extends unknown // For distributing `Type` ? (keyof {[Key in keyof Type as IsOptionalKeyOf extends false ? never : Key ]: never }) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf` is always assignable to `keyof Type` : never; // Should never happen /** 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 = RequiredKeysOf, >(field: Key, validator: (value: Entity[Key]) => boolean): (entity: Entity) => boolean; type User = { name: string; surname: string; luckyNumber?: number; }; const validator1 = createValidation('name', value => value.length < 25); const validator2 = createValidation('surname', value => value.length < 25); // @ts-expect-error const validator3 = createValidation('luckyNumber', value => value > 0); // Error: Argument of type '"luckyNumber"' is not assignable to parameter of type '"name" | "surname"'. ``` @category Utilities */ type RequiredKeysOf = Type extends unknown // For distributing `Type` ? Exclude> : never; // Should never happen /** 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'; type A = IsNever; //=> true type B = IsNever; //=> false type C = IsNever; //=> false type D = IsNever; //=> false type E = IsNever; //=> false type F = IsNever; //=> false ``` @example ``` import type {IsNever} from 'type-fest'; type IsTrue = T extends true ? true : false; // When a distributive conditional is instantiated with `never`, the entire conditional results in `never`. type A = IsTrue; //=> never // If you don't want that behaviour, you can explicitly add an `IsNever` check before the distributive conditional. type IsTrueFixed = IsNever extends true ? false : T extends true ? true : false; type B = IsTrueFixed; //=> false ``` @category Type Guard @category Utilities */ type IsNever = [T] extends [never] ? true : false; /** 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 extends UnknownArray ? true : false; type A = IsArray<['foo']>; //=> true type B = IsArray; //=> true type C = IsArray; //=> false ``` @category Type @category Array */ type UnknownArray = readonly unknown[]; /** Matches any primitive, `void`, `Date`, or `RegExp` value. */ type BuiltIns = Primitive | void | Date | RegExp; /** Matches non-recursive types. */ type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown) | Promise; /** 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; ``` 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`. 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 = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify` 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; declare function fn(object: Record): void; fn(literal); // Good: literal object type is sealed fn(someType); // Good: type is sealed // @ts-expect-error fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened fn(someInterface as Simplify); // Good: transform an `interface` into a `type` ``` @link https://github.com/microsoft/TypeScript/issues/15300 @see {@link SimplifyDeep} @category Object */ type Simplify = {[KeyType in keyof T]: T[KeyType]} & {}; /** 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 [Value[0], ...infer rest] ? IsEqual extends true ? true : Includes : false; ``` @category Type Guard @category Utilities */ type IsEqual = [A] extends [B] ? [B] extends [A] ? _IsEqual : false : false; // This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`. type _IsEqual = (() => G extends A & G | G ? 1 : 2) extends (() => G extends B & G | G ? 1 : 2) ? true : false; /** Extract all possible values for a given key from a union of object types. @example ``` type Statuses = ValueOfUnion<{id: 1; status: 'open'} | {id: 2; status: 'closed'}, 'status'>; //=> "open" | "closed" ``` */ type ValueOfUnion> = Union extends unknown ? Key extends keyof Union ? Union[Key] : never : never; /** Extract all readonly keys from a union of object types. @example ``` type User = { readonly id: string; name: string; }; type Post = { readonly id: string; readonly author: string; body: string; }; type ReadonlyKeys = ReadonlyKeysOfUnion; //=> "id" | "author" ``` */ type ReadonlyKeysOfUnion = Union extends unknown ? keyof { [Key in keyof Union as IsEqual<{[K in Key]: Union[Key]}, {readonly [K in Key]: Union[Key]}> extends true ? Key : never]: never } : never; /** Create a type with shared fields from a union of object types. Use-cases: - You want a safe object type where each key exists in the union object. - You want to focus on the common fields of the union type and don't want to have to care about the other fields. @example ``` import type {SharedUnionFields} from 'type-fest'; type Cat = { name: string; type: 'cat'; catType: string; }; type Dog = { name: string; type: 'dog'; dogType: string; }; function displayPetInfo(petInfo: Cat | Dog) { // typeof petInfo => // { // name: string; // type: 'cat'; // catType: string; // Needn't care about this field, because it's not a common pet info field. // } | { // name: string; // type: 'dog'; // dogType: string; // Needn't care about this field, because it's not a common pet info field. // } // petInfo type is complex and have some needless fields console.log('name:', petInfo.name); console.log('type:', petInfo.type); } function displayPetInfoWithSharedUnionFields(petInfo: SharedUnionFields) { // typeof petInfo => // { // name: string; // type: 'cat' | 'dog'; // } // petInfo type is simple and clear console.log('name:', petInfo.name); console.log('type:', petInfo.type); } ``` @see {@link SharedUnionFieldsDeep} @see {@link AllUnionFields} @category Object @category Union */ type SharedUnionFields = Extract | ReadonlySet | UnknownArray> extends infer SkippedMembers ? Exclude extends infer RelevantMembers ? | SkippedMembers | (IsNever extends true ? never : Simplify>) : never : never; /** Create a type with all fields from a union of object types. Use-cases: - You want a safe object type where each key exists in the union object. @example ``` import type {AllUnionFields} from 'type-fest'; type Cat = { name: string; type: 'cat'; catType: string; }; type Dog = { name: string; type: 'dog'; dogType: string; }; function displayPetInfo(petInfo: Cat | Dog) { // typeof petInfo => // { // name: string; // type: 'cat'; // catType: string; // } | { // name: string; // type: 'dog'; // dogType: string; // } console.log('name:', petInfo.name); console.log('type:', petInfo.type); // TypeScript complains about `catType` and `dogType` not existing on type `Cat | Dog`. // @ts-expect-error console.log('animal type:', petInfo.catType ?? petInfo.dogType); } function displayPetInfoWithAllUnionFields(petInfo: AllUnionFields) { // typeof petInfo => // { // name: string; // type: 'cat' | 'dog'; // catType?: string; // dogType?: string; // } console.log('name:', petInfo.name); console.log('type:', petInfo.type); // No TypeScript error. console.log('animal type:', petInfo.catType ?? petInfo.dogType); } ``` @see {@link SharedUnionFields} @category Object @category Union */ type AllUnionFields = Extract | ReadonlySet | UnknownArray> extends infer SkippedMembers ? Exclude extends infer RelevantMembers ? | SkippedMembers | Simplify< // Include fields that are common in all union members SharedUnionFields & // Include readonly fields present in any union member { readonly [P in ReadonlyKeysOfUnion]?: ValueOfUnion> } & // Include remaining fields that are neither common nor readonly { [P in Exclude, ReadonlyKeysOfUnion | keyof RelevantMembers>]?: ValueOfUnion } > : never : never; /** * Type helper to get all unique keys of an array of objects. If there are no keys, it returns `string[]` to allow for any keys. * @template T - The type of values in the input objects. * @returns An array of unique keys present in the input objects, or `string[]` if there are no keys. * @example ```ts * const objects = [ * { a: 1, b: 2, d: 4 }, * { a: 1, b: 2, c: 3 }, * ]; * type AllKeysOfObjects = AllKeys; * //=> "a" | "b" | "d" | "c" * ``` */ type AllKeys = (keyof AllUnionFields)[] extends never[] ? string[] : (keyof AllUnionFields)[]; /** * Type helper to get the common keys of an array of objects. If there are no common keys, it returns `string[]` to allow for any keys. * @template T - The type of values in the input objects. * @returns An array of keys that are present in all input objects, or `string[]` if there are no common keys. * @example ```ts * const objects = [ * { a: 1, b: 2, d: 4 }, * { a: 1, b: 2, c: 3 }, * ]; * type CommonKeysOfObjects = CommonKeys; * //=> "a" | "b" * ``` */ type CommonKeys = RequiredKeysOf & object>[] extends never[] ? string[] : RequiredKeysOf & object>[]; /** * Returns an array of keys that are common to all objects in the input array. * @template T - The type of values in the input objects. * @returns An array of keys that are present in all input objects. * @param objects The array of objects. * @example ```ts * const objects = [ * { a: 1, b: 2, d: 4 }, * { a: 1, b: 2, c: 3 }, * ]; * arrObjectsCommonKeys(objects); * //=> ['a', 'b'] // ("a" | "b")[] * ``` */ declare function arrObjectsCommonKeys(objects: T): CommonKeys; /** * Convert an array of objects to a two-dimensional table. * @param objects The array of objects to convert to a table. * @template T - The type of the values in the objects. * @param options.headers An optional array of strings specifying the headers (property names) to use. If not provided, the function will use all unique keys found in the objects. * @param options.emptyCell An optional value to use for empty cells. If not provided, the function will use `undefined`. * @returns A 2D array (table) where each row represents an object and each column represents a property of the object. * @param options The options for converting the objects to a table. * @example ```ts * arrObjectsToTable( * [ * { a: 1, b: 2 }, * { a: 3, b: 4, c: 5 }, * ], * { emptyCell:1 }, * ) //=> [ [ 'a', 'b', 'c' ], [ 1, 2,1 ], [ 3, 4, 5 ] ] * ``` */ declare function arrObjectsToTable(objects: Record[], options?: { headers?: string[]; emptyCell?: E; }): Array>; /** * Returns an array of all unique object keys found in an array of objects. * @template T - The type of values in the input objects. * @returns An array of unique keys present in the input objects. * @param objects The array of objects. * @example ```ts * const objects = [ * { a: 1, b: 2, d: 4 }, * { a: 1, b: 2, c: 3 }, * ]; * arrObjectsUniqueKeys(objects); * //=> ['a', 'b', 'd', 'c'] // ("a" | "b" | "d" | "c")[] * ``` */ declare function arrObjectsUniqueKeys(objects: T): AllKeys; /** * Sorts an array of numbers, bigints, or booleans in ascending order. * @returns The sorted array. * @remarks This function uses the JavaScript `Array.prototype.sort()` method, which sorts elements in place. * Therefore, the original array will be modified. * @throws If any element in the input array is not a number, bigint, or boolean. * @param input The array to be sorted. * @example ```ts * const input = [5, 2n, true, 10, false]; * arrSortNumeric(input); * //=> [false, true, 2n, 5, 10] * ``` */ declare function arrSortNumeric(input: Array): Array; /** * Returns an index in the sorted array where the specified value could be inserted while maintaining the sorted order of the array. * If the element is already in the array, returns the index after the last instance of the element. * @param array - The sorted array to search. * @param value - The value to locate in the array. * @param comparator - A function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. * @returns The index at which the value could be inserted into array to maintain the array's sorted order. * @example ```ts * const array = [1, 2, 3, 5, 6]; * const value = 4; * const comparator = (a, b) => a - b; * const index = arrSortedLowerBound(array, value, comparator); * console.log(index); // Output: 3 * ``` */ declare function arrSortedInsertionIndex(array: readonly T[], value: T, comparator: (a: T, b: T) => number): number; /** * Swaps two elements in an array. This function takes an input array and swaps the elements at the specified indices. * @param to The index of the element to swap to. * @param from The index of the element to swap from. * @template T - The type of elements in the array. * @returns The modified array with swapped elements. * @throws Will throw an error if 'from' or 'to' is not a valid index in the array. * @param input The input array. * @example ```ts * const arr = [1, 2, 3, 4, 5] * arrSwap(arr, 1, 3) //=> [1, 4, 3, 2, 5] * ``` */ declare function arrSwap(input: Array, from: number, to: number): Array; /** * Asserts that all rows in a 2D array have the same length. * @param - Optional array of headers to compare the row length against. * @throws If any row in the array has a different length than the others. * @param headers Optional. An array of headers. If provided, each row must have the same length as this array. * @typeparam T - The type of elements in the rows. * @param rows The 2D array to check. * @example ```ts * const rows = [ * [1, 2, 3], * [4, 5, 6], * [7, 8, 9], * ]; * arrTableAssertRowsSameLength(rows); * //=> undefined * const rowsWithDifferentLength = [ * [1, 2, 3], * [4, 5], * [7, 8, 9], * ]; * arrTableAssertRowsSameLength(rowsWithDifferentLength); * //=> Error: Expected 3 columns, got 2 * ``` */ declare function arrTableAssertRowsSameLength(rows: T[][], headers?: string[]): void; /** * Coerce each value of a 2D array table to string. * @template T - The type of the elements in the input array. * @returns The converted 2D array where each element is a string. * @param table The 2D array to convert. * @example ```ts * const input: number[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; * arrTableEachToString(input); * //=> [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] * ``` */ declare function arrTableEachToString(table: T[][]): string[][]; /** * Generator that iterates through a 2D array table, yielding objects with header keys and row values. */ declare function arrTableIterateAsObjects(rows: T[][], headers: string[], ignoreHeaders?: Set): Generator, void, unknown>; /** * Removes specified columns from a 2D array table. * @param table - The 2D array (table) from which columns will be removed. The first row of the table is assumed to contain column names. * @param removeColumnNames - The names of the columns to be removed. These should match the entries in the first row of the table. * @returns A new 2D array (table) with the specified columns removed. */ declare function arrTableRemoveColumns(table: string[][], ...removeColumnNames: string[]): string[][]; /** * Converts a 2D array to a CSV string. * @param input The input 2D array. * @remarks This function is useful for exporting data to CSV format. * @param replaceLinebreakWith The character used to replace line breaks in the CSV string. Defaults to '|'. * @typeparam T - The type of the elements in the input array. * @returns The CSV string representation of the input array. * @param delimiter The delimiter to use for separating values in the CSV string. * @example ```ts * const input = [ * ['Name', 'Age', 'Country'], * ['John', '25', 'USA'], * ['Alice', '30', 'Canada'], * ['Bob', '35', 'UK'], * ]; * arrTableToCsv(input); * //=> "Name;Age;Country\nJohn;25;USA\nAlice;30;Canada\nBob;35;UK" * ``` */ declare function arrTableToCsv(input: T[][], delimiter?: string, replaceLinebreakWith?: string): string; /** * Converts a 2D array representing a table into an array of objects. * @param rows The 2D array representing the table. * @template T - The type of the elements in the rows. * @param headers The headers to use as keys for the objects. If not provided, the first row of the table is used as headers. * @returns An array of objects, where each object represents a row in the table. * @throws Throws an error if the headers are not provided and the table is empty or only contains one row. * @param headers Optional array of headers for the table. * @example ```ts * const table = [ * ['Name', 'Age', 'Country'], * ['John', 25, 'USA'], * ['Jane', 30, 'Canada'], * ]; * const headers = ['Name', 'Age', 'Country']; * arrTableToObjects(table, headers) //=> [ * // { Name: 'John', Age: 25, Country: 'USA' }, * // { Name: 'Jane', Age: 30, Country: 'Canada' }, * // ] * ``` */ declare function arrTableToObjects(rows: T[][], headers?: string[], ignoreKeys?: Set): Record[]; export { arrFindIndices, arrGetOrDefault, arrHasDuplicates, arrIndicesOf, arrMapMutable, arrObjectsCommonKeys, arrObjectsToTable, arrObjectsUniqueKeys, arrSortNumeric, arrSortedInsertionIndex, arrSwap, arrTableAssertRowsSameLength, arrTableEachToString, arrTableIterateAsObjects, arrTableRemoveColumns, arrTableToCsv, arrTableToObjects };