/** Matches an [`abstract class`](https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-classes-and-members). @category Class @privateRemarks We cannot use a `type` here because TypeScript throws: 'abstract' modifier cannot appear on a type member. (1070) */ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export declare interface AbstractClass extends AbstractConstructor { prototype: Pick; } /** Matches an [`abstract class`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html#abstract-construct-signatures) constructor. @category Class */ export declare type AbstractConstructor = abstract new(...arguments_: Arguments) => T; /** Returns a boolean for whether every element in an array type extends another type. @example ``` import type {AllExtend} from 'type-fest'; type A = AllExtend<[1, 2, 3], number>; //=> true type B = AllExtend<[1, 2, '3'], number>; //=> false type C = AllExtend<[number, number | string], number>; //=> boolean type D = AllExtend<[true, boolean, true], true>; //=> boolean ``` Note: Behaviour of optional elements depend on the `exactOptionalPropertyTypes` compiler option. When the option is disabled, the target type must include `undefined` for a successful match. ``` import type {AllExtend} from 'type-fest'; // `exactOptionalPropertyTypes` enabled type A = AllExtend<[1?, 2?, 3?], number>; //=> true // `exactOptionalPropertyTypes` disabled type B = AllExtend<[1?, 2?, 3?], number>; //=> false // `exactOptionalPropertyTypes` disabled type C = AllExtend<[1?, 2?, 3?], number | undefined>; //=> true ``` @see {@link AllExtendOptions} @category Utilities @category Array */ export declare type AllExtend = _AllExtend, Type, ApplyDefaultOptions>; declare type _AllExtend> = IfNotAnyOrNever, true, TArray extends readonly [infer First, ...infer Rest] ? IsNever extends true ? Or, Not> extends true // If target `Type` is also `never` OR `strictNever` is disabled, recurse further. ? _AllExtend : false : First extends Type ? _AllExtend : false : true >, false, false>; /** @see {@link AllExtend} */ export declare type AllExtendOptions = { /** Consider `never` elements to match the target type only if the target type itself is `never` (or `any`). - When set to `true` (default), `never` is _not_ treated as a bottom type, instead, it is treated as a type that matches only itself (or `any`). - When set to `false`, `never` is treated as a bottom type, and behaves as it normally would. @default true @example ``` import type {AllExtend} from 'type-fest'; type A = AllExtend<[1, 2, never], number, {strictNever: true}>; //=> false type B = AllExtend<[1, 2, never], number, {strictNever: false}>; //=> true type C = AllExtend<[never, never], never, {strictNever: true}>; //=> true type D = AllExtend<[never, never], never, {strictNever: false}>; //=> true type E = AllExtend<['a', 'b', never], any, {strictNever: true}>; //=> true type F = AllExtend<['a', 'b', never], any, {strictNever: false}>; //=> true type G = AllExtend<[never, 1], never, {strictNever: true}>; //=> false type H = AllExtend<[never, 1], never, {strictNever: false}>; //=> false ``` */ strictNever?: boolean; }; /** 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 */ export declare 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; /** Matches any lowercase letter (a-z), uppercase letter (A-Z), or digit ('0'-'9') in the basic Latin alphabet. @example ``` import type {Alphanumeric} from 'type-fest'; const a: Alphanumeric = 'A'; // Valid // @ts-expect-error const b: Alphanumeric = '#'; // Invalid ``` @category Type */ export declare type Alphanumeric = LowercaseLetter | UppercaseLetter | DigitCharacter; /** Returns a boolean for whether two given types are both true. Use-case: Constructing complex conditional types where multiple conditions must be satisfied. @example ``` import type {And} from 'type-fest'; type TT = And; //=> true type TF = And; //=> false type FT = And; //=> false type FF = And; //=> false ``` Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases. For example, `And` expands to `And | And`, which simplifies to `true | false` (i.e., `boolean`). @example ``` import type {And} from 'type-fest'; type A = And; //=> boolean type B = And; //=> boolean type C = And; //=> false type D = And; //=> false type E = And; //=> boolean ``` Note: If either of the types is `never`, the result becomes `false`. @example ``` import type {And} from 'type-fest'; type A = And; //=> false type B = And; //=> false type C = And; //=> false type D = And; //=> false type E = And; //=> false type F = And; //=> false type G = And; //=> false ``` @see {@link Or} @see {@link Xor} */ export declare type And = AllExtend<[A, B], true>; /** 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; //=> {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; // ~~~~~~~~~~~~~~~~~~~ // 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; // ~~~~~~~~~~~~~~~~~~~ // 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; // ~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` */ declare type ApplyDefaultOptions< Options extends object, Defaults extends Simplify, RequiredKeysOf> & Partial, never>>>, SpecifiedOptions extends Options, > = If, Defaults, If, Defaults, Simplify ? undefined extends SpecifiedOptions[Key] ? never : Key : Key ]: SpecifiedOptions[Key] }> & Required>>>; /** Create a type that represents either the value or an array of the value. @see {@link Promisable} @example ``` import type {Arrayable} from 'type-fest'; function bundle(input: string, output: Arrayable) { const outputList = Array.isArray(output) ? output : [output]; // … for (const output of outputList) { console.log(`write ${input} to: ${output}`); } } bundle('src/index.js', 'dist/index.js'); bundle('src/index.js', ['dist/index.cjs', 'dist/index.mjs']); ``` @category Array */ export declare type Arrayable = T // TODO: Use `readonly T[]` when this issue is resolved: https://github.com/microsoft/TypeScript/issues/17002 | T[]; /** Extracts the element type of an array or tuple. Use-cases: - When you need type-safe element extraction that returns `never` for non-arrays. - When extracting element types from generic array parameters in function signatures. - For better readability and explicit intent over using `T[number]` directly. Note: Returns `never` if the type is not an array. @example ``` import type {ArrayElement} from 'type-fest'; // Arrays type StringArray = ArrayElement; //=> string // Tuples type Tuple = ArrayElement<[1, 2, 3]>; //=> 1 | 2 | 3 // Type-safe type NotArray = ArrayElement<{a: string}>; //=> never // Practical example declare function getRandomElement(array: T): ArrayElement; getRandomElement(['foo', 'bar', 'baz'] as const); //=> 'foo' | 'bar' | 'baz' ``` @see {@link ArrayValues} - For directly extracting values from a constant array type. @see {@link IterableElement} - For iterables like `Set`, `Map`, and generators (not suitable for all use cases due to different inference behavior). @category Array */ export declare type ArrayElement = T extends UnknownArray ? T[number] : never; declare type ArrayEntries = Array<_ArrayEntry>; declare type _ArrayEntry = [number, BaseType[number]]; /** Provides valid indices for a constant array or tuple. Use-case: This type is useful when working with constant arrays or tuples and you want to enforce type-safety for accessing elements by their indices. @example ``` import type {ArrayIndices, ArrayValues} from 'type-fest'; const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as const; type Weekday = ArrayIndices; type WeekdayName = ArrayValues; const getWeekdayName = (day: Weekday): WeekdayName => weekdays[day]; ``` @see {@link ArrayValues} @category Array */ export declare type ArrayIndices = Exclude['length'], Element['length']>; /** Methods to exclude. */ declare type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'; /** Merge mode for array/tuple elements. */ declare type ArrayMergeMode = 'spread' | 'replace'; /** Returns an array slice of a given range, just like `Array#slice()`. @example ``` import type {ArraySlice} from 'type-fest'; type T0 = ArraySlice<[0, 1, 2, 3, 4]>; //=> [0, 1, 2, 3, 4] type T1 = ArraySlice<[0, 1, 2, 3, 4], 0, -1>; //=> [0, 1, 2, 3] type T2 = ArraySlice<[0, 1, 2, 3, 4], 1, -2>; //=> [1, 2] type T3 = ArraySlice<[0, 1, 2, 3, 4], -2, 4>; //=> [3] type T4 = ArraySlice<[0, 1, 2, 3, 4], -2, -1>; //=> [3] type T5 = ArraySlice<[0, 1, 2, 3, 4], 0, -999>; //=> [] function arraySlice< const Array_ extends readonly unknown[], Start extends number = 0, End extends number = Array_['length'], >(array: Array_, start?: Start, end?: End) { return array.slice(start, end) as ArraySlice; } const slice = arraySlice([1, '2', {a: 3}, [4, 5]], 0, -1); type Slice = typeof slice; //=> [1, '2', { readonly a: 3; }] const value = slice[2].a; //=> 3 // @ts-expect-error -- TS2493: Tuple type '[1, "2", {readonly a: 3}]' of length '3' has no element at index '3'. const invalidIndexAccess = slice[3]; ``` @category Array */ export declare type ArraySlice< Array_ extends readonly unknown[], Start extends number = never, End extends number = never, > = Array_ extends unknown // To distributive type ? IsNever extends true ? IsNever extends true ? _ArraySlice : End extends unknown // To distribute `End` ? _ArraySlice : never // Never happens : IsNever extends true ? Start extends unknown // To distribute `Start` ? _ArraySlice : never // Never happens : Start extends unknown // To distribute `Start` ? End extends unknown // To distribute `End` ? _ArraySlice : never // Never happens : never // Never happens : never; declare type _ArraySlice< Array_ extends readonly unknown[], Start extends number = 0, End extends number = Array_['length'], > = And, IsEqual> extends true ? Array_ : number extends Array_['length'] ? VariableLengthArraySliceHelper : ArraySliceHelper extends true ? 0 : Start, IsEqual extends true ? Array_['length'] : End>; declare type ArraySliceByPositiveIndex< Array_ extends readonly unknown[], Start extends number, End extends number, Result extends Array = [], > = Start extends End ? Result : ArraySliceByPositiveIndex, End, [...Result, Array_[Start]]>; declare type ArraySliceHelper< Array_ extends readonly unknown[], Start extends number = 0, End extends number = Array_['length'], TraversedElement extends Array = [], Result extends Array = [], ArrayLength extends number = Array_['length'], PositiveS extends number = IsNegative extends true ? Sum extends infer AddResult extends number ? number extends AddResult // (ArrayLength + Start) < 0 ? 0 : GreaterThan extends true ? AddResult : 0 : never : Start, PositiveE extends number = IsNegative extends true ? Sum : End, > = true extends [IsNegative, LessThanOrEqual, GreaterThanOrEqual][number] ? [] : ArraySliceByPositiveIndex, TupleMin<[PositiveE, ArrayLength]>>; /** Create a new array type by adding or removing elements at a specified index range in the original array. Use-case: Replace or insert items in an array type. Like [`Array#splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) but for types. @example ``` import type {ArraySplice} from 'type-fest'; type SomeMonths0 = ['January', 'April', 'June']; type Months0 = ArraySplice; //=> ['January', 'Feb', 'March', 'April', 'June']; type SomeMonths1 = ['January', 'April', 'June']; type Months1 = ArraySplice; //=> ['January', 'June']; type SomeMonths2 = ['January', 'Foo', 'April']; type Months2 = ArraySplice; //=> ['January', 'Feb', 'March', 'April']; ``` @category Array */ export declare type ArraySplice< T extends UnknownArray, Start extends number, DeleteCount extends number, Items extends UnknownArray = [], > = SplitArrayByIndex extends [infer U extends UnknownArray, infer V extends UnknownArray] ? SplitArrayByIndex extends [infer _Deleted extends UnknownArray, infer X extends UnknownArray] ? [...U, ...Items, ...X] : never // Should never happen : never; /** Extract the type of an array or tuple minus the first element. @example ``` import type {ArrayTail} from 'type-fest'; type A = ArrayTail<[1, 2, 3]>; //=> [2, 3] type B = ArrayTail; //=> readonly [2, 3] type C = ArrayTail<[1, 2, 3?, ...string[]]>; //=> [2, 3?, ...string[]] type D = ArrayTail; //=> readonly [] type E = ArrayTail<[]>; //=> [] type F = ArrayTail; //=> string[] type G = ArrayTail; //=> readonly [...string[], 1, 2] ``` @example ``` import type {ArrayTail} from 'type-fest'; type Curry = Func extends (...agruments_: infer Arguments) => infer Return ? Arguments extends readonly [] ? Return : (agrument: Arguments[0]) => Curry<(...agruments_: ArrayTail) => Return> : never; declare function curry(fn: Func): Curry; declare function searchBooks(genre: string, minRating: number, available: boolean): string[]; const availableTopSciFi = curry(searchBooks)('sci-fi')(4.5)(true); //=> string[] ``` @category Array */ export declare type ArrayTail = IfNotAnyOrNever extends infer Result ? If, Readonly, Result> : never // Should never happen : never >; declare type _ArrayTail = TArray extends readonly [unknown?, ...infer Tail] ? keyof TArray & `${number}` extends never ? TArray extends readonly [] ? [] : TArray // Happens when `TArray` is a non-tuple array (e.g., `string[]`) or has a leading rest element (e.g., `[...string[], number]`) : Tail : []; declare type ArrayTail_2 = TArray extends unknown // For distributing `TArray` ? keyof TArray & `${number}` extends never ? [] : Writable_2> : never; /** Provides all values for a constant array or tuple. Use-case: This type is useful when working with constant arrays or tuples and you want to enforce type-safety with their values. @example ``` import type {ArrayValues, ArrayIndices} from 'type-fest'; const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as const; type WeekdayName = ArrayValues; type Weekday = ArrayIndices; const getWeekdayName = (day: Weekday): WeekdayName => weekdays[day]; ``` @see {@link ArrayIndices} @category Array */ export declare type ArrayValues = T[number]; declare type AsciiPunctuation = | '!' | '"' | '#' | '$' | '%' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '_' | '`' | '{' | '|' | '}' | '~'; /** Assert the condition according to the {@link ConditionalPickDeepOptions.condition|condition} option. */ declare type AssertCondition = Options['condition'] extends 'equality' ? IsEqual : Type extends Condition ? true : false; declare type AsyncFunction = (...arguments_: any[]) => PromiseLike; /** Create an async version of the given function type, by boxing the return type in `Promise` while keeping the same parameter types. Use-case: You have two functions, one synchronous and one asynchronous that do the same thing. Instead of having to duplicate the type definition, you can use `Asyncify` to reuse the synchronous type. @example ``` import type {Asyncify} from 'type-fest'; // Synchronous function type Config = {featureFlags: Record}; declare function loadConfigSync(path: string): Config; type LoadConfigAsync = Asyncify; //=> (path: string) => Promise ``` @category Async */ export declare type Asyncify any> = SetReturnType>>>; /** Unwrap the return type of a function that returns a `Promise`. There has been [discussion](https://github.com/microsoft/TypeScript/pull/35998) about implementing this type in TypeScript. @example ```ts import type {AsyncReturnType} from 'type-fest'; declare function asyncFunction(): Promise<{foo: string}>; // This type resolves to the unwrapped return type of `asyncFunction`. type Value = AsyncReturnType; //=> {foo: string} declare function doSomething(value: Value): void; const value = await asyncFunction(); doSomething(value); ``` @category Async */ export declare type AsyncReturnType = Awaited>; declare type BaseKeyFilter = Key extends symbol ? never : Type[Key] extends symbol ? never /* To prevent a problem where an object with only a `name` property is incorrectly treated as assignable to a function, we first check if the property is a record. This check is necessary, because without it, if we don't verify whether the property is a record, an object with a type of `{name: any}` would return `never` due to its potential assignability to a function. See: https://github.com/sindresorhus/type-fest/issues/657 */ : Type[Key] extends Record ? Key : [(...arguments_: any[]) => any] extends [Type[Key]] ? never : Key; /** Create an object type with the given key `` and value ``. It will copy the prefix and optional status of the same key from the given object `CopiedFrom` into the result. @example ``` type A = BuildObject<'a', string>; //=> {a: string} // Copy `readonly` and `?` from the key `a` of `{readonly a?: any}` type B = BuildObject<'a', string, {readonly a?: any}>; //=> {readonly a?: string} ``` */ declare type BuildObject = Key extends keyof CopiedFrom ? Pick<{[_ in keyof CopiedFrom]: Value}, Key> : Key extends `${infer NumberKey extends number}` ? NumberKey extends keyof CopiedFrom ? Pick<{[_ in keyof CopiedFrom]: Value}, NumberKey> : {[_ in Key]: Value} : {[_ in Key]: Value}; /** Matches any primitive, `void`, `Date`, or `RegExp` value. */ declare type BuiltIns = Primitive | void | Date | RegExp; /** Convert a string literal to camel-case. This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result. By default, consecutive uppercase letter are preserved. See {@link CamelCaseOptions.preserveConsecutiveUppercase preserveConsecutiveUppercase} option to change this behaviour. @example ``` import type {CamelCase} from 'type-fest'; // Simple const someVariable: CamelCase<'foo-bar'> = 'fooBar'; const preserveConsecutiveUppercase: CamelCase<'foo-BAR-baz', {preserveConsecutiveUppercase: true}> = 'fooBARBaz'; // Advanced type CamelCasedProperties = { [K in keyof T as CamelCase]: T[K] }; type RawOptions = { 'dry-run': boolean; 'full_family_name': string; foo: number; BAR: string; QUZ_QUX: number; 'OTHER-FIELD': boolean; }; const dbResult: CamelCasedProperties = { dryRun: true, fullFamilyName: 'bar.js', foo: 123, bar: 'foo', quzQux: 6, otherField: false, }; ``` @category Change case @category Template literal */ export declare type CamelCase = Type extends string ? string extends Type ? Type : Uncapitalize ? Lowercase : Type, Options>, ApplyDefaultOptions >> : Type; /** Convert object properties to camel case but not recursively. This can be useful when, for example, converting some API types from a different style. @see {@link CamelCasedPropertiesDeep} @see {@link CamelCase} @example ``` import type {CamelCasedProperties} from 'type-fest'; type User = { UserId: number; UserName: string; }; const result: CamelCasedProperties = { userId: 1, userName: 'Tom', }; const preserveConsecutiveUppercase: CamelCasedProperties<{fooBAR: string}, {preserveConsecutiveUppercase: true}> = { fooBAR: 'string', }; ``` @category Change case @category Template literal @category Object */ export declare type CamelCasedProperties = Value extends Function ? Value : Value extends Array ? Value : { [K in keyof Value as CamelCase> ]: Value[K]; }; declare type CamelCasedPropertiesArrayDeep< Value extends UnknownArray, Options extends Required, > = Value extends [] ? [] // Trailing spread array : Value extends [infer U, ...infer V] ? [_CamelCasedPropertiesDeep, ..._CamelCasedPropertiesDeep] : Value extends readonly [infer U, ...infer V] ? readonly [_CamelCasedPropertiesDeep, ..._CamelCasedPropertiesDeep] : // Leading spread array Value extends readonly [...infer U, infer V] ? [..._CamelCasedPropertiesDeep, _CamelCasedPropertiesDeep] : // Array Value extends Array ? Array<_CamelCasedPropertiesDeep> : Value extends ReadonlyArray ? ReadonlyArray<_CamelCasedPropertiesDeep> : never; /** Convert object properties to camel case recursively. This can be useful when, for example, converting some API types from a different style. @see {@link CamelCasedProperties} @see {@link CamelCase} @example ``` import type {CamelCasedPropertiesDeep} from 'type-fest'; type User = { UserId: number; UserName: string; }; type UserWithFriends = { UserInfo: User; UserFriends: User[]; }; const result: CamelCasedPropertiesDeep = { userInfo: { userId: 1, userName: 'Tom', }, userFriends: [ { userId: 2, userName: 'Jerry', }, { userId: 3, userName: 'Spike', }, ], }; const preserveConsecutiveUppercase: CamelCasedPropertiesDeep<{fooBAR: {fooBARBiz: [{fooBARBaz: string}]}}, {preserveConsecutiveUppercase: true}> = { fooBAR: { fooBARBiz: [{ fooBARBaz: 'string', }], }, }; ``` @category Change case @category Template literal @category Object */ export declare type CamelCasedPropertiesDeep< Value, Options extends CamelCaseOptions = {}, > = _CamelCasedPropertiesDeep>; declare type _CamelCasedPropertiesDeep< Value, Options extends Required, > = Value extends NonRecursiveType ? Value : Value extends UnknownArray ? CamelCasedPropertiesArrayDeep : Value extends Set ? Set<_CamelCasedPropertiesDeep> : Value extends object ? { [K in keyof Value as CamelCase]: _CamelCasedPropertiesDeep; } : Value; /** Convert an array of words to camel-case. */ declare type CamelCaseFromArray< Words extends string[], Options extends Required, OutputString extends string = '', > = Words extends [ infer FirstWord extends string, ...infer RemainingWords extends string[], ] ? Options['preserveConsecutiveUppercase'] extends true ? `${Capitalize}${CamelCaseFromArray}` : `${Capitalize>}${CamelCaseFromArray}` : OutputString; /** CamelCase options. @see {@link CamelCase} */ export declare type CamelCaseOptions = WordsOptions & { /** Whether to preserved consecutive uppercase letter. @default false */ preserveConsecutiveUppercase?: boolean; }; /** Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). @category Class */ export declare type Class = { prototype: Pick; new(...arguments_: Arguments): T; }; /** Collapses literal types in a union into their corresponding primitive types, when possible. For example, `CollapseLiterals<'foo' | 'bar' | (string & {})>` returns `string`. Note: This doesn't collapse literals within tagged types. For example, `CollapseLiterals>` returns `("foo" & Tag<"Tag", never>) | (string & Tag<"Tag", never>)` and not `string & Tag<"Tag", never>`. Use-case: For collapsing unions created using {@link LiteralUnion}. @example ``` import type {LiteralUnion} from 'type-fest'; type A = CollapseLiterals<'foo' | 'bar' | (string & {})>; //=> string type B = CollapseLiterals>; //=> number type C = CollapseLiterals>; //=> `on${string}` type D = CollapseLiterals<'click' | 'change' | (`on${string}` & {})>; //=> 'click' | 'change' | `on${string}` type E = CollapseLiterals | null | undefined>; //=> string | null | undefined ``` */ declare type CollapseLiterals = {} extends T ? T : T extends infer U & {} ? U : T; /** Transforms a tuple type by replacing it's rest element with a single element that has the same type as the rest element, while keeping all the non-rest elements intact. @example ``` type A = CollapseRestElement<[string, string, ...number[]]>; //=> [string, string, number] type B = CollapseRestElement<[...string[], number, number]>; //=> [string, number, number] type C = CollapseRestElement<[string, string, ...Array]>; //=> [string, string, number | bigint] type D = CollapseRestElement<[string, number]>; //=> [string, number] ``` Note: Optional modifiers (`?`) are removed from elements unless the `exactOptionalPropertyTypes` compiler option is disabled. When disabled, there's an additional `| undefined` for optional elements. @example ``` // `exactOptionalPropertyTypes` enabled type A = CollapseRestElement<[string?, string?, ...number[]]>; //=> [string, string, number] // `exactOptionalPropertyTypes` disabled type B = CollapseRestElement<[string?, string?, ...number[]]>; //=> [string | undefined, string | undefined, number] ``` */ declare type CollapseRestElement = IfNotAnyOrNever>; declare type _CollapseRestElement< TArray extends UnknownArray, ForwardAccumulator extends UnknownArray = [], BackwardAccumulator extends UnknownArray = [], > = TArray extends UnknownArray // For distributing `TArray` ? keyof TArray & `${number}` extends never // Enters this branch, if `TArray` is empty (e.g., []), // or `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`). ? TArray extends readonly [...infer Rest, infer Last] ? _CollapseRestElement // Accumulate elements that are present after the rest element. : TArray extends readonly [] ? [...ForwardAccumulator, ...BackwardAccumulator] : [...ForwardAccumulator, TArray[number], ...BackwardAccumulator] // Add the rest element between the accumulated elements. : TArray extends readonly [(infer First)?, ...infer Rest] ? _CollapseRestElement< Rest, [ ...ForwardAccumulator, '0' extends OptionalKeysOf ? If // Add `| undefined` for optional elements, if `exactOptionalPropertyTypes` is disabled. : First, ], BackwardAccumulator > : never // Should never happen, since `[(infer First)?, ...infer Rest]` is a top-type for arrays. : never; /** Exclude keys from a shape that matches the given `Condition`. This is useful when you want to create a new type with a specific set of keys from a shape. For example, you might want to exclude all the primitive properties from a class and form a new shape containing everything but the primitive properties. @example ``` import type {Primitive, ConditionalExcept} from 'type-fest'; class Awesome { constructor(public name: string, public successes: number, public failures: bigint) {} run() { // do something } } type ExceptPrimitivesFromAwesome = ConditionalExcept; //=> {run: () => void} ``` @example ``` import type {ConditionalExcept} from 'type-fest'; type Example = { a: string; b: string | number; c: () => void; d: {}; }; type NonStringKeysOnly = ConditionalExcept; //=> {b: string | number; c: () => void; d: {}} ``` @category Object */ export declare type ConditionalExcept = Except< Base, ConditionalKeys >; /** Extract the keys from a type where the value type of the key extends the given `Condition`. Internally this is used for the `ConditionalPick` and `ConditionalExcept` types. @example ``` import type {ConditionalKeys} from 'type-fest'; type Example = { a: string; b: string | number; c?: string; d: {}; }; type StringKeysOnly = ConditionalKeys; //=> 'a' ``` Note: To extract optional keys, make sure your `Condition` is a union of `undefined` (for example, `string | undefined`) as demonstrated below. @example ``` import type {ConditionalKeys} from 'type-fest'; type StringKeysAndUndefined = ConditionalKeys<{a?: string}, string | undefined>; //=> 'a' type NoMatchingKeys = ConditionalKeys<{a?: string}, string>; //=> never ``` You can also extract array indices whose value match the specified condition, as shown below: ``` import type {ConditionalKeys} from 'type-fest'; type StringValueIndices = ConditionalKeys<[string, number, string], string>; //=> '0' | '2' type NumberValueIndices = ConditionalKeys<[string, number?, string?], number | undefined>; //=> '1' ``` @category Object */ export declare type ConditionalKeys = (Base extends UnknownArray ? TupleToObject : Base) extends infer _Base // Remove non-numeric keys from arrays ? IfNotAnyOrNever<_Base, _ConditionalKeys<_Base, Condition>, keyof _Base> : never; declare type _ConditionalKeys = keyof { [ Key in (keyof Base & {}) as // `& {}` prevents homomorphism ExtendsStrict extends true ? Key : never ]: never }; /** Pick keys from the shape that matches the given `Condition`. This is useful when you want to create a new type from a specific subset of an existing type. For example, you might want to pick all the primitive properties from a class and form a new automatically derived type. @example ``` import type {Primitive, ConditionalPick} from 'type-fest'; class Awesome { constructor(public name: string, public successes: number, public failures: bigint) {} run() { // do something } } type PickPrimitivesFromAwesome = ConditionalPick; //=> {name: string; successes: number; failures: bigint} ``` @example ``` import type {ConditionalPick} from 'type-fest'; type Example = { a: string; b: string | number; c: () => void; d: {}; }; type StringKeysOnly = ConditionalPick; //=> {a: string} ``` @category Object */ export declare type ConditionalPick = Pick< Base, ConditionalKeys >; /** Pick keys recursively from the shape that matches the given condition. @see {@link ConditionalPick} @example ``` import type {ConditionalPickDeep} from 'type-fest'; type Example = { a: string; b: string | boolean; c: { d: string; e: { f?: string; g?: boolean; h: string | boolean; i: boolean | bigint; }; j: boolean; }; }; type StringPick = ConditionalPickDeep; //=> {a: string; c: {d: string}} type StringPickOptional = ConditionalPickDeep; //=> {a: string; c: {d: string; e: {f?: string}}} type StringPickOptionalOnly = ConditionalPickDeep; //=> {c: {e: {f?: string}}} type BooleanPick = ConditionalPickDeep; //=> {c: {e: {g?: boolean}; j: boolean}} type NumberPick = ConditionalPickDeep; //=> {} type StringOrBooleanPick = ConditionalPickDeep; //=> { // a: string; // b: string | boolean; // c: { // d: string; // e: { // h: string | boolean // }; // j: boolean; // }; // } type StringOrBooleanPickOnly = ConditionalPickDeep; //=> {b: string | boolean; c: {e: {h: string | boolean}}} ``` @category Object */ export declare type ConditionalPickDeep< Type, Condition, Options extends ConditionalPickDeepOptions = {}, > = _ConditionalPickDeep< Type, Condition, ApplyDefaultOptions >; declare type _ConditionalPickDeep< Type, Condition, Options extends Required, > = ConditionalSimplifyDeep extends true ? Type[Key] : IsPlainObject extends true ? _ConditionalPickDeep : typeof conditionalPickDeepSymbol; }, (typeof conditionalPickDeepSymbol | undefined) | EmptyObject>, never, UnknownRecord>; /** ConditionalPickDeep options. @see {@link ConditionalPickDeep} */ export declare type ConditionalPickDeepOptions = { /** The condition assertion mode. @default 'extends' */ condition?: 'extends' | 'equality'; }; /** Used to mark properties that should be excluded. */ declare const conditionalPickDeepSymbol: unique symbol; /** Simplifies a type while including and/or excluding certain types from being simplified. Useful to improve type hints shown in editors. And also to transform an `interface` into a `type` to aid with assignability. @example ``` import type {ConditionalSimplify} from 'type-fest'; type TypeA = { a: string; }; type TypeB = { b: string; }; type TypeAB = TypeA & TypeB; //=> TypeA & TypeB type SimplifyTypeAB = ConditionalSimplify; //=> {a: string; b: string} ``` @example ``` import type {ConditionalSimplify} from 'type-fest'; type Simplify = ConditionalSimplify | Map | unknown[], object>; type A = Simplify & Set>; //=> Set & Set type B = Simplify & Map>; //=> Map & Map type C = Simplify<{a: number} & {b: string}>; //=> {a: number; b: string} ``` @see {@link ConditionalSimplifyDeep} @category Object */ export declare type ConditionalSimplify = Type extends ExcludeType ? Type : Type extends IncludeType ? {[TypeKey in keyof Type]: Type[TypeKey]} : Type; /** Recursively simplifies a type while including and/or excluding certain types from being simplified. @example ``` import type {ConditionalSimplifyDeep} from 'type-fest'; type TypeA = { foo: { a: string; }; }; type TypeB = { foo: { b: string; }; }; type SimplifyDeepTypeAB = ConditionalSimplifyDeep; //=> {foo: {a: string; b: string}} ``` @example ``` import type {ConditionalSimplifyDeep} from 'type-fest'; type SomeComplexType1 = { a1: string; b1: number; c1: boolean; }; type SomeComplexType2 = { a2: string; b2: number; c2: boolean; }; type TypeA = { foo: { a: string; complexType: SomeComplexType1; }; }; type TypeB = { foo: { b: string; complexType: SomeComplexType2; }; }; type SimplifyDeepTypeAB = ConditionalSimplifyDeep; //=> { // foo: { // a: string; // b: string; // complexType: SomeComplexType1 & SomeComplexType2; // }; // } ``` @see {@link SimplifyDeep} @category Object */ export declare type ConditionalSimplifyDeep = Type extends ExcludeType ? Type : Type extends IncludeType ? {[TypeKey in keyof Type]: ConditionalSimplifyDeep} : Type; /** Returns true if `LongString` is made up out of `Substring` repeated 0 or more times. @example ``` type A = ConsistsOnlyOf<'aaa', 'a'>; //=> true type B = ConsistsOnlyOf<'ababab', 'ab'>; //=> true type C = ConsistsOnlyOf<'aBa', 'a'>; //=> false type D = ConsistsOnlyOf<'', 'a'>; //=> true ``` */ declare type ConsistsOnlyOf = LongString extends '' ? true : LongString extends `${Substring}${infer Tail}` ? ConsistsOnlyOf : false; /** Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). @category Class */ export declare type Constructor = new(...arguments_: Arguments) => T; declare type DefaultAllExtendOptions = { strictNever: true; }; declare type _DefaultCamelCaseOptions = { splitOnNumbers: true; preserveConsecutiveUppercase: false; }; declare type DefaultConditionalPickDeepOptions = { condition: 'extends'; }; declare type _DefaultDelimiterCaseOptions = Merge<_DefaultWordsOptions, {splitOnNumbers: false}>; declare type DefaultExceptOptions = { requireExactProps: false; }; declare type DefaultGetOptions = { strict: true; }; declare type DefaultIsTupleOptions = { fixedLengthOnly: true; }; /** Merge default and internal options with user provided options. */ declare type DefaultMergeDeepOptions = Merge<{ arrayMergeMode: 'replace'; recurseIntoArrays: false; spreadTopLevelArrays: true; }, Options>; declare type DefaultPartialDeepOptions = { recurseIntoArrays: false; allowUndefinedInNonTupleArrays: false; }; declare type DefaultPartialOnUndefinedDeepOptions = { recurseIntoArrays: false; }; declare type DefaultPathsOptions = { maxRecursionDepth: 5; bracketNotation: false; leavesOnly: false; depth: number; }; declare type DefaultRemovePrefixOptions = { strict: true; }; declare type DefaultReplaceOptions = { all: false; }; declare type DefaultSchemaOptions = { recurseIntoArrays: true; }; declare type DefaultSetFieldTypeOptions = { preservePropertyModifiers: true; }; declare type DefaultSharedUnionFieldsDeepOptions = { recurseIntoArrays: false; }; declare type DefaultSplitOnRestElementOptions = { preserveOptionalModifier: true; }; declare type DefaultSplitOptions = { strictLiteralChecks: true; }; declare type _DefaultWordsOptions = { splitOnNumbers: true; }; /** Convert a string literal to a custom string delimiter casing. This can be useful when, for example, converting a camel-cased object property to an oddly cased one. @see {@link KebabCase} @see {@link SnakeCase} @example ``` import type {DelimiterCase} from 'type-fest'; // Simple const someVariable: DelimiterCase<'fooBar', '#'> = 'foo#bar'; const someVariableNoSplitOnNumbers: DelimiterCase<'p2pNetwork', '#', {splitOnNumbers: false}> = 'p2p#network'; // Advanced type OddlyCasedProperties = { [K in keyof T as DelimiterCase]: T[K] }; type SomeOptions = { dryRun: boolean; includeFile: string; foo: number; }; const rawCliOptions: OddlyCasedProperties = { 'dry#run': true, 'include#file': 'bar.js', foo: 123, }; ``` @category Change case @category Template literal */ export declare type DelimiterCase< Value, Delimiter extends string, Options extends WordsOptions = {}, > = Value extends string ? IsStringLiteral extends false ? Value : Lowercase>, Delimiter >, string, {strict: false}>> : Value; /** Convert object properties to delimiter case but not recursively. This can be useful when, for example, converting some API types from a different style. @see {@link DelimiterCase} @see {@link DelimiterCasedPropertiesDeep} @example ``` import type {DelimiterCasedProperties} from 'type-fest'; type User = { userId: number; userName: string; }; const result: DelimiterCasedProperties = { 'user-id': 1, 'user-name': 'Tom', }; const splitOnNumbers: DelimiterCasedProperties<{line1: string}, '-', {splitOnNumbers: true}> = { 'line-1': 'string', }; ``` @category Change case @category Template literal @category Object */ export declare type DelimiterCasedProperties< Value, Delimiter extends string, Options extends WordsOptions = {}, > = Value extends Function ? Value : Value extends Array ? Value : {[K in keyof Value as DelimiterCase> ]: Value[K]}; declare type DelimiterCasedPropertiesArrayDeep< Value extends UnknownArray, Delimiter extends string, Options extends Required, > = Value extends [] ? [] // Trailing spread array : Value extends [infer U, ...infer V] ? [_DelimiterCasedPropertiesDeep, ..._DelimiterCasedPropertiesDeep] : Value extends readonly [infer U, ...infer V] ? readonly [_DelimiterCasedPropertiesDeep, ..._DelimiterCasedPropertiesDeep] // Leading spread array : Value extends [...infer U, infer V] ? [..._DelimiterCasedPropertiesDeep, _DelimiterCasedPropertiesDeep] : Value extends readonly [...infer U, infer V] ? readonly [..._DelimiterCasedPropertiesDeep, _DelimiterCasedPropertiesDeep] // Array : Value extends Array ? Array<_DelimiterCasedPropertiesDeep> : Value extends ReadonlyArray ? ReadonlyArray<_DelimiterCasedPropertiesDeep> : never; /** Convert object properties to delimiter case recursively. This can be useful when, for example, converting some API types from a different style. @see {@link DelimiterCase} @see {@link DelimiterCasedProperties} @example ``` import type {DelimiterCasedPropertiesDeep} from 'type-fest'; type User = { userId: number; userName: string; }; type UserWithFriends = { userInfo: User; userFriends: User[]; }; const result: DelimiterCasedPropertiesDeep = { 'user-info': { 'user-id': 1, 'user-name': 'Tom', }, 'user-friends': [ { 'user-id': 2, 'user-name': 'Jerry', }, { 'user-id': 3, 'user-name': 'Spike', }, ], }; const splitOnNumbers: DelimiterCasedPropertiesDeep<{line1: {line2: [{line3: string}]}}, '-', {splitOnNumbers: true}> = { 'line-1': { 'line-2': [ { 'line-3': 'string', }, ], }, }; ``` @category Change case @category Template literal @category Object */ export declare type DelimiterCasedPropertiesDeep< Value, Delimiter extends string, Options extends WordsOptions = {}, > = _DelimiterCasedPropertiesDeep>; declare type _DelimiterCasedPropertiesDeep< Value, Delimiter extends string, Options extends Required, > = Value extends NonRecursiveType ? Value : Value extends UnknownArray ? DelimiterCasedPropertiesArrayDeep : Value extends Set ? Set<_DelimiterCasedPropertiesDeep> : Value extends object ? { [K in keyof Value as DelimiterCase]: _DelimiterCasedPropertiesDeep } : Value; /** Convert an array of words to delimiter case starting with a delimiter with input capitalization. */ declare type DelimiterCaseFromArray< Words extends string[], Delimiter extends string, OutputString extends string = '', > = Words extends [ infer FirstWord extends string, ...infer RemainingWords extends string[], ] ? DelimiterCaseFromArray extends true ? '' : Delimiter }${FirstWord}`> : OutputString; /** Matches any digit as a string ('0'-'9'). @example ``` import type {DigitCharacter} from 'type-fest'; const a: DigitCharacter = '0'; // Valid // @ts-expect-error const b: DigitCharacter = 0; // Invalid ``` @category Type */ export declare type DigitCharacter = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'; /** Omits keys from a type, distributing the operation over a union. TypeScript's `Omit` doesn't distribute over unions, leading to the erasure of unique properties from union members when omitting keys. This creates a type that only retains properties common to all union members, making it impossible to access member-specific properties after the Omit. Essentially, using `Omit` on a union type merges the types into a less specific one, hindering type narrowing and property access based on discriminants. This type solves that. Example: ``` type A = { discriminant: 'A'; foo: string; a: number; }; type B = { discriminant: 'B'; foo: string; b: string; }; type Union = A | B; type OmittedUnion = Omit; //=> {discriminant: 'A' | 'B'} declare const omittedUnion: OmittedUnion; if (omittedUnion.discriminant === 'A') { // We would like to narrow `omittedUnion`'s type // to `A` here, but we can't because `Omit` // doesn't distribute over unions. // @ts-expect-error const aValue = omittedUnion.a; //=> Error: `a` is not a property of `{discriminant: 'A' | 'B'}` } ``` While `Except` solves this problem, it restricts the keys you can omit to the ones that are present in **ALL** union members, where `DistributedOmit` allows you to omit keys that are present in **ANY** union member. @example ``` import type {DistributedOmit} from 'type-fest'; type A = { discriminant: 'A'; foo: string; a: number; }; type B = { discriminant: 'B'; foo: string; bar: string; b: string; }; type C = { discriminant: 'C'; bar: string; c: boolean; }; // Notice that `foo` exists in `A` and `B`, but not in `C`, and // `bar` exists in `B` and `C`, but not in `A`. type Union = A | B | C; type OmittedUnion = DistributedOmit; declare const omittedUnion: OmittedUnion; if (omittedUnion.discriminant === 'A') { const aValue = omittedUnion.a; //=> OK // @ts-expect-error const fooValue = omittedUnion.foo; //=> Error: `foo` is not a property of `{discriminant: 'A'; a: string}` // @ts-expect-error const barValue = omittedUnion.bar; //=> Error: `bar` is not a property of `{discriminant: 'A'; a: string}` } ``` @category Object */ export declare type DistributedOmit> = ObjectType extends unknown ? Omit : never; /** Pick keys from a type, distributing the operation over a union. TypeScript's `Pick` doesn't distribute over unions, leading to the erasure of unique properties from union members when picking keys. This creates a type that only retains properties common to all union members, making it impossible to access member-specific properties after the Pick. Essentially, using `Pick` on a union type merges the types into a less specific one, hindering type narrowing and property access based on discriminants. This type solves that. Example: ``` type A = { discriminant: 'A'; foo: { bar: string; }; }; type B = { discriminant: 'B'; foo: { baz: string; }; }; type Union = A | B; type PickedUnion = Pick; //=> {discriminant: 'A' | 'B', foo: {bar: string} | {baz: string}} declare const pickedUnion: PickedUnion; if (pickedUnion.discriminant === 'A') { // We would like to narrow `pickedUnion`'s type // to `A` here, but we can't because `Pick` // doesn't distribute over unions. // @ts-expect-error const barValue = pickedUnion.foo.bar; //=> Error: Property 'bar' does not exist on type '{bar: string} | {baz: string}'. } ``` @example ``` import type {DistributedPick} from 'type-fest'; type A = { discriminant: 'A'; foo: { bar: string; }; extraneous: boolean; }; type B = { discriminant: 'B'; foo: { baz: string; }; extraneous: boolean; }; // Notice that `foo.bar` exists in `A` but not in `B`. type Union = A | B; type PickedUnion = DistributedPick; declare const pickedUnion: PickedUnion; if (pickedUnion.discriminant === 'A') { const barValue = pickedUnion.foo.bar; //=> OK // @ts-expect-error const extraneousValue = pickedUnion.extraneous; //=> Error: Property `extraneous` does not exist on type `Pick`. // @ts-expect-error const bazValue = pickedUnion.foo.baz; //=> Error: `bar` is not a property of `{discriminant: 'A'; a: string}`. } ``` @category Object */ export declare type DistributedPick> = ObjectType extends unknown ? Pick> : never; /** Merge two arrays/tuples according to the chosen {@link MergeDeepOptions.arrayMergeMode arrayMergeMode} option. */ declare type DoMergeArrayOrTuple< Destination extends UnknownArrayOrTuple, Source extends UnknownArrayOrTuple, Options extends MergeDeepInternalOptions, > = ShouldSpread extends true ? Array[number] | Exclude[number]> : Source; /** Walk through the union of the keys of the two objects and test in which object the properties are defined. Rules: 1. If the source does not contain the key, the value of the destination is returned. 2. If the source contains the key and the destination does not contain the key, the value of the source is returned. 3. If both contain the key, try to merge according to the chosen {@link MergeDeepOptions options} or return the source if unable to merge. */ declare type DoMergeDeepRecord< Destination extends UnknownRecord, Source extends UnknownRecord, Options extends MergeDeepInternalOptions, > = // Case in rule 1: The destination contains the key but the source doesn't. { [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key]; } // Case in rule 2: The source contains the key but the destination doesn't. & { [Key in keyof Source as Key extends keyof Destination ? never : Key]: Source[Key]; } // Case in rule 3: Both the source and the destination contain the key. & { [Key in keyof Source as Key extends keyof Destination ? Key : never]: MergeDeepRecordProperty; }; /** Merge two tuples recursively. */ declare type DoMergeDeepTupleAndTupleRecursive< Destination extends UnknownArrayOrTuple, Source extends UnknownArrayOrTuple, DestinationRestType, SourceRestType, Options extends MergeDeepInternalOptions, > = Destination extends [] ? Source extends [] ? [] : MergeArrayTypeAndTuple : Source extends [] ? MergeTupleAndArrayType : [ MergeDeepArrayOrTupleElements, FirstArrayElement, Options>, ...DoMergeDeepTupleAndTupleRecursive, ArrayTail_2, DestinationRestType, SourceRestType, Options>, ]; /** Represents a strictly empty plain object, the `{}` value. When you annotate something as the type `{}`, it can be anything except `null` and `undefined`. This means that you cannot use `{}` to represent an empty plain object ([read more](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference/52193484#52193484)). @example ``` import type {EmptyObject} from 'type-fest'; // The following illustrates the problem with `{}`. const foo1: {} = {}; // Pass const foo2: {} = []; // Pass const foo3: {} = 42; // Pass const foo4: {} = {a: 1}; // Pass // With `EmptyObject` only the first case is valid. const bar1: EmptyObject = {}; // Pass // @ts-expect-error const bar2: EmptyObject = []; // Fail // @ts-expect-error const bar3: EmptyObject = 42; // Fail // @ts-expect-error const bar4: EmptyObject = {a: 1}; // Fail ``` Unfortunately, `Record`, `Record` and `Record` do not work. See {@link https://github.com/sindresorhus/type-fest/issues/395 #395}. @category Object */ export declare type EmptyObject = {[emptyObjectSymbol]?: never}; declare const emptyObjectSymbol: unique symbol; /** Enforce optional keys (by adding the `?` operator) for keys that have a union with `undefined`. @example ``` import type {EnforceOptional} from 'type-fest'; type Foo = { a: string; b?: string; c: undefined; d: number | undefined; }; type FooBar = EnforceOptional; // => { // a: string; // b?: string; // c: undefined; // d?: number; // } ``` @internal @category Object */ declare type EnforceOptional = Simplify<{ [Key in keyof ObjectType as RequiredFilter]: ObjectType[Key] } & { [Key in keyof ObjectType as OptionalFilter]?: Exclude }>; /** Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entries` type will return the type of that collection's entries. For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable. @see `Entry` if you want to just access the type of a single entry. @example ``` import type {Entries} from 'type-fest'; type Example = { someKey: number; }; const manipulatesEntries = (examples: Entries) => examples.map(example => [ // Does some arbitrary processing on the key (with type information available) example[0].toUpperCase(), // Does some arbitrary processing on the value (with type information available) example[1].toFixed(0), ]); const example: Example = {someKey: 1}; const entries = Object.entries(example) as Entries; const output = manipulatesEntries(entries); // Objects const objectExample = {a: 1}; const objectEntries: Entries = [['a', 1]]; // Arrays const arrayExample = ['a', 1]; const arrayEntries: Entries = [[0, 'a'], [1, 1]]; // Maps const mapExample = new Map([['a', 1]]); const mapEntries: Entries = [['a', 1]]; // Sets const setExample = new Set(['a', 1]); const setEntries: Entries = [['a', 'a'], [1, 1]]; ``` @category Object @category Map @category Set @category Array */ export declare type Entries = BaseType extends Map ? MapEntries : BaseType extends Set ? SetEntries : BaseType extends readonly unknown[] ? ArrayEntries : BaseType extends object ? ObjectEntries : never; /** Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entry` type will return the type of that collection's entry. For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable. @see `Entries` if you want to just access the type of the array of entries (which is the return of the `.entries()` method). @example ``` import type {Entry} from 'type-fest'; type Example = { someKey: number; }; const manipulatesEntry = (example: Entry) => [ // Does some arbitrary processing on the key (with type information available) example[0].toUpperCase(), // Does some arbitrary processing on the value (with type information available) example[1].toFixed(0), ]; const example: Example = {someKey: 1}; const entry = Object.entries(example)[0] as Entry; const output = manipulatesEntry(entry); // Objects const objectExample = {a: 1}; const objectEntry: Entry = ['a', 1]; // Arrays const arrayExample = ['a', 1]; const arrayEntryString: Entry = [0, 'a']; const arrayEntryNumber: Entry = [1, 1]; // Maps const mapExample = new Map([['a', 1]]); const mapEntry: Entry = ['a', 1]; // Sets const setExample = new Set(['a', 1]); const setEntryString: Entry = ['a', 'a']; const setEntryNumber: Entry = [1, 1]; ``` @category Object @category Map @category Array @category Set */ export declare type Entry = BaseType extends Map ? _MapEntry : BaseType extends Set ? _SetEntry : BaseType extends readonly unknown[] ? _ArrayEntry : BaseType extends object ? _ObjectEntry : never; /** Create a type that does not allow extra properties, meaning it only allows properties that are explicitly declared. This is useful for function type-guarding to reject arguments with excess properties. Due to the nature of TypeScript, it does not complain if excess properties are provided unless the provided value is an object literal. *Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/12936) if you want to have this type as a built-in in TypeScript.* @example ``` type OnlyAcceptName = {name: string}; declare function onlyAcceptName(arguments_: OnlyAcceptName): void; // TypeScript complains about excess properties when an object literal is provided. // @ts-expect-error onlyAcceptName({name: 'name', id: 1}); //=> `id` is excess // TypeScript does not complain about excess properties when the provided value is a variable (not an object literal). const invalidInput = {name: 'name', id: 1}; onlyAcceptName(invalidInput); // No errors ``` Having `Exact` allows TypeScript to reject excess properties. @example ``` import type {Exact} from 'type-fest'; type OnlyAcceptName = {name: string}; declare function onlyAcceptNameImproved>(arguments_: T): void; const invalidInput = {name: 'name', id: 1}; // @ts-expect-error onlyAcceptNameImproved(invalidInput); // Compilation error ``` [Read more](https://stackoverflow.com/questions/49580725/is-it-possible-to-restrict-typescript-object-to-contain-only-properties-defined) @category Utilities */ export declare type Exact = // Before distributing, check if the two types are equal and if so, return the parameter type immediately IsEqual extends true ? ParameterType // If the parameter is a primitive, return it as is immediately to avoid it being converted to a complex type : ParameterType extends Primitive ? ParameterType // If the parameter is an unknown, return it as is immediately to avoid it being converted to a complex type : IsUnknown extends true ? unknown // If the parameter is a Function, return it as is because this type is not capable of handling function, leave it to TypeScript : ParameterType extends Function ? ParameterType // Convert union of array to array of union: A[] & B[] => (A & B)[] : ParameterType extends unknown[] ? Array, ArrayElement>> // In TypeScript, Array is a subtype of ReadonlyArray, so always test Array before ReadonlyArray. : ParameterType extends readonly unknown[] ? ReadonlyArray, ArrayElement>> : ExactObject; /** Get the exact version of the given `Key` in the given object `T`. Use-case: You know that a number key (e.g. 10) is in an object, but you don't know how it is defined in the object, as a string or as a number (e.g. 10 or '10'). You can use this type to get the exact version of the key. See the example. @example ``` type Object = { 0: number; '1': string; }; type Key1 = ExactKey; //=> 0 type Key2 = ExactKey; //=> 0 type Key3 = ExactKey; //=> '1' type Key4 = ExactKey; //=> '1' ``` @category Object */ declare type ExactKey = Key extends keyof T ? Key : ToString extends keyof T ? ToString : Key extends `${infer NumberKey extends number}` ? NumberKey extends keyof T ? NumberKey : never : never; /** Create a type from `ParameterType` and `InputType` and change keys exclusive to `InputType` to `never`. - Generate a list of keys that exists in `InputType` but not in `ParameterType`. - Mark these excess keys as `never`. */ declare type ExactObject = {[Key in keyof ParameterType]: Exact>} & Record>, never>; /** 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; //=> {b: string} // @ts-expect-error const fooWithoutA: FooWithoutA = {a: 1, b: '2'}; //=> errors: 'a' does not exist in type '{ b: string; }' type FooWithoutB = Except; //=> {a: number} & Partial> // @ts-expect-error 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; //=> { [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 PostPayloadFixed = Except; //=> { [x: string]: string; name: string; role: 'admin' | 'user'; } ``` @category Object */ export declare type Except = _Except>; declare type _Except> = { [KeyType in keyof ObjectType as Filter]: ObjectType[KeyType]; } & (Options['requireExactProps'] extends true ? Partial> : {}); export declare 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; }; /** Create a tuple with the [`rest`](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) element removed. @example ``` import type {ExcludeRestElement} from 'type-fest'; type T1 = ExcludeRestElement<[number, ...string[], string, 'foo']>; //=> [number, string, 'foo'] type T2 = ExcludeRestElement<[...boolean[], string]>; //=> [string] type T3 = ExcludeRestElement<[...Array<'foo'>, true]>; //=> [true] type T4 = ExcludeRestElement<[number, string]>; //=> [number, string] ``` @see {@link ExtractRestElement} @see {@link SplitOnRestElement} @category Array */ export declare type ExcludeRestElement = IfNotAnyOrNever extends infer Result ? Result extends readonly UnknownArray[] ? IsArrayReadonly extends true ? Readonly<[...Result[0], ...Result[2]]> : [...Result[0], ...Result[2]] : never : never >; /** A stricter version of {@link Exclude} that ensures every member of `U` can successfully exclude something from `T`. For example, `ExcludeStrict` will error because `bigint` cannot exclude anything from `string | number | boolean`. @example ``` // Valid Examples import type {ExcludeStrict} from 'type-fest'; type Example1 = ExcludeStrict<{status: 'success'; data: string[]} | {status: 'error'; error: string}, {status: 'success'}>; //=> {status: 'error'; error: string} type Example2 = ExcludeStrict<'xs' | 's' | 'm' | 'l' | 'xl', 'xs' | 's'>; //=> 'm' | 'l' | 'xl' type Example3 = ExcludeStrict<{x: number; y: number} | [number, number], unknown[]>; //=> {x: number; y: number} ``` @example ``` // Invalid Examples import type {ExcludeStrict} from 'type-fest'; // `'xxl'` cannot exclude anything from `'xs' | 's' | 'm' | 'l' | 'xl'` // @ts-expect-error type Example1 = ExcludeStrict<'xs' | 's' | 'm' | 'l' | 'xl', 'xl' | 'xxl'>; // ~~~~~~~~~~~~ // Error: Type "'xl' | 'xxl'" does not satisfy the constraint 'never'. // `unknown[]` cannot exclude anything from `{x: number; y: number} | {x: string; y: string}` // @ts-expect-error type Example2 = ExcludeStrict<{x: number; y: number} | {x: string; y: string}, unknown[]>; // ~~~~~~~~~ // Error: Type 'unknown[]' does not satisfy the constraint 'never'. ``` @category Improved Built-in */ export declare type ExcludeStrict< T, U extends [U] extends [ // Ensure every member of `U` excludes something from `T` U extends unknown ? ([T] extends [Exclude] ? never : U) : never, ] ? unknown : never, > = Exclude; /** Ensure mutual exclusivity in object unions by adding other members’ keys as `?: never`. Use-cases: - You want each union member to be exclusive, preventing overlapping object shapes. - You want to safely access any property defined across the union without additional type guards. @example ``` import type {ExclusifyUnion} from 'type-fest'; type FileConfig = { filePath: string; }; type InlineConfig = { content: string; }; declare function loadConfig1(options: FileConfig | InlineConfig): void; // Someone could mistakenly provide both `filePath` and `content`. loadConfig1({filePath: './config.json', content: '{ "name": "app" }'}); // No errors // Use `ExclusifyUnion` to prevent that mistake. type Config = ExclusifyUnion; //=> {filePath: string; content?: never} | {content: string; filePath?: never} declare function loadConfig2(options: Config): void; // @ts-expect-error loadConfig2({filePath: './config.json', content: '{ "name": "app" }'}); //=> Error: Argument of type '{ filePath: string; content: string; }' is not assignable to parameter of type '{ filePath: string; content?: never; } | { content: string; filePath?: never; }'. loadConfig2({filePath: './config.json'}); // Ok loadConfig2({content: '{ "name": "app" }'}); // Ok ``` @example ``` import type {ExclusifyUnion} from 'type-fest'; type CardPayment = { amount: number; cardNumber: string; }; type PaypalPayment = { amount: number; paypalId: string; }; function processPayment1(payment: CardPayment | PaypalPayment) { // @ts-expect-error const details = payment.cardNumber ?? payment.paypalId; // Cannot access `cardNumber` or `paypalId` directly } type Payment = ExclusifyUnion; //=> {amount: number; cardNumber: string; paypalId?: never} | {amount: number; paypalId: string; cardNumber?: never} function processPayment2(payment: Payment) { const details = payment.cardNumber ?? payment.paypalId; // Ok //=> string } ``` @example ``` import type {ExclusifyUnion} from 'type-fest'; type A = ExclusifyUnion<{a: string} | {b: number}>; //=> {a: string; b?: never} | {a?: never; b: number} type B = ExclusifyUnion<{a: string} | {b: number} | {c: boolean}>; //=> {a: string; b?: never; c?: never} | {a?: never; b: number; c?: never} | {a?: never; b?: never; c: boolean} type C = ExclusifyUnion<{a: string; b: number} | {b: string; c: number}>; //=> {a: string; b: number; c?: never} | {a?: never; b: string; c: number} type D = ExclusifyUnion<{a?: 1; readonly b: 2} | {d: 4}>; //=> {a?: 1; readonly b: 2; d?: never} | {a?: never; b?: never; d: 4} ``` @category Object @category Union */ export declare type ExclusifyUnion = IfNotAnyOrNever, Union, Extract extends infer SkippedMembers ? SkippedMembers | _ExclusifyUnion> : never > >; declare type _ExclusifyUnion = Union extends unknown // For distributing `Union` ? Simplify< Union & Partial< Record< Exclude, keyof Union>, never > > > : never; /** A stricter, non-distributive version of `extends` for checking whether one type is assignable to another. Unlike the built-in `extends` keyword, `ExtendsStrict`: 1. Prevents distribution over union types by wrapping both types in tuples. For example, `ExtendsStrict` returns `false`, whereas `string | number extends number` would result in `boolean`. 2. Treats `never` as a special case: `never` doesn't extend every other type, it only extends itself (or `any`). For example, `ExtendsStrict` returns `false` whereas `never extends number` would result in `true`. @example ``` import type {ExtendsStrict} from 'type-fest'; type T1 = ExtendsStrict; //=> false type T2 = ExtendsStrict; //=> false type T3 = ExtendsStrict; //=> true type T4 = ExtendsStrict; //=> true type T5 = ExtendsStrict; //=> true ``` @category Improved Built-in */ export declare type ExtendsStrict = IsAny extends true ? true : IsNever extends true ? IsNever : [Left] extends [Right] ? true : false; /** Extract the [`rest`](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) element type from an array. @example ``` import type {ExtractRestElement} from 'type-fest'; type T1 = ExtractRestElement<[number, ...string[], string, 'foo']>; //=> string type T2 = ExtractRestElement<[...boolean[], string]>; //=> boolean type T3 = ExtractRestElement<[...Array<'foo'>, true]>; //=> 'foo' type T4 = ExtractRestElement<[number, string]>; //=> never ``` @see {@link ExcludeRestElement} @see {@link SplitOnRestElement} @category Array */ export declare type ExtractRestElement = SplitOnRestElement[1][number]; /** A stricter version of {@link Extract} that ensures every member of `U` can successfully extract something from `T`. For example, `ExtractStrict` will error because `bigint` cannot extract anything from `string | number | boolean`. @example ``` // Valid Examples import type {ExtractStrict} from 'type-fest'; type Example1 = ExtractStrict<{status: 'success'; data: string[]} | {status: 'error'; error: string}, {status: 'success'}>; //=> {status: 'success'; data: string[]} type Example2 = ExtractStrict<'xs' | 's' | 'm' | 'l' | 'xl', 'xs' | 's'>; //=> 'xs' | 's' type Example3 = ExtractStrict<{x: number; y: number} | [number, number], unknown[]>; //=> [number, number] ``` @example ``` // Invalid Examples import type {ExtractStrict} from 'type-fest'; // `'xxl'` cannot extract anything from `'xs' | 's' | 'm' | 'l' | 'xl'` // @ts-expect-error type Example1 = ExtractStrict<'xs' | 's' | 'm' | 'l' | 'xl', 'xl' | 'xxl'>; // ~~~~~~~~~~~~ // Error: Type "'xl' | 'xxl'" does not satisfy the constraint 'never'. // `unknown[]` cannot extract anything from `{x: number; y: number} | {x: string; y: string}` // @ts-expect-error type Example2 = ExtractStrict<{x: number; y: number} | {x: string; y: string}, unknown[]>; // ~~~~~~~~~ // Error: Type 'unknown[]' does not satisfy the constraint 'never'. ``` @category Improved Built-in */ export declare type ExtractStrict< T, U extends [U] extends [ // Ensure every member of `U` extracts something from `T` U extends unknown ? (Extract extends never ? never : U) : never, ] ? unknown : never, > = Extract; /** 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} */ declare type Filter = IsEqual extends true ? never : (KeyType extends ExcludeType ? never : KeyType); /** Returns the required keys. */ declare type FilterDefinedKeys = Exclude< { [Key in keyof T]: IsAny extends true ? Key : IsUnknown extends true ? Key : undefined extends T[Key] ? never : T[Key] extends undefined ? never : BaseKeyFilter; }[keyof T], undefined >; declare type FilterJsonableKeys = { [Key in keyof T]: T[Key] extends NotJsonable ? never : Key; }[keyof T]; /** Returns the optional keys. */ declare type FilterOptionalKeys = Exclude< { [Key in keyof T]: IsAny extends true ? never : undefined extends T[Key] ? T[Key] extends undefined ? never : BaseKeyFilter : never; }[keyof T], undefined >; /** Tries to find one or more types from their globally-defined constructors. Use-case: Conditionally referencing DOM types only when the DOM library present. *Limitations:* Due to peculiarities with the behavior of `globalThis`, "globally defined" has a narrow definition in this case. Declaring a class in a `declare global` block won't work, instead you must declare its type using an interface and declare its constructor as a `var` (*not* `let`/`const`) inside the `declare global` block. @example ``` import type {FindGlobalInstanceType} from 'type-fest'; class Point { constructor(public x: number, public y: number) {} } type PointLike = Point | FindGlobalInstanceType<'DOMPoint'>; ``` @example ``` import type {FindGlobalInstanceType} from 'type-fest'; declare global { // Class syntax won't add the key to `globalThis` class Foo {} // interface + constructor style works interface Bar { bar: string; } var Bar: new () => Bar; // Not let or const } type FindFoo = FindGlobalInstanceType<'Foo'>; // Doesn't work type FindBar = FindGlobalInstanceType<'Bar'>; // Works ``` @category Utilities */ export declare type FindGlobalInstanceType = Name extends string ? typeof globalThis extends Record infer T> ? T : never : never; /** Tries to find the type of a global with the given name. Limitations: Due to peculiarities with the behavior of `globalThis`, "globally defined" only includes `var` declarations in `declare global` blocks, not `let` or `const` declarations. @example ``` import type {FindGlobalType} from 'type-fest'; declare global { const foo: number; // let and const don't work var bar: string; // var works } type FooType = FindGlobalType<'foo'>; //=> never (let/const don't work) type BarType = FindGlobalType<'bar'>; //=> string type OtherType = FindGlobalType<'other'>; //=> never (no global named 'other') ``` @category Utilities */ export declare type FindGlobalType = typeof globalThis extends Record ? T : never; /** A finite `number`. You can't pass a `bigint` as they are already guaranteed to be finite. Use-case: Validating and documenting parameters. Note: This can't detect `NaN`, please upvote [this issue](https://github.com/microsoft/TypeScript/issues/28682) if you want to have this type as a built-in in TypeScript. @example ``` import type {Finite} from 'type-fest'; declare function setScore(length: Finite): void; ``` @category Numeric */ export declare type Finite = T extends PositiveInfinity | NegativeInfinity ? never : T; /** Extracts the type of the first element of an array or tuple. */ declare type FirstArrayElement = TArray extends readonly [infer THead, ...unknown[]] ? THead : never; /** Create a type that represents an array of the given type and length. The `Array` prototype methods that manipulate its length are excluded from the resulting type. The problem with the built-in tuple type is that it allows mutating methods like `push`, `pop` etc, which can cause issues, like in the following example: @example ``` const color: [number, number, number] = [255, 128, 64]; function toHex([r, g, b]: readonly [number, number, number]) { return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`; } color.pop(); // Allowed console.log(toHex(color)); // Compiles fine, but fails at runtime since index `2` no longer contains a `number`. ``` `ArrayLengthMutationKeys` solves this problem by excluding methods like `push`, `pop` etc from the resulting type. @example ``` import type {FixedLengthArray} from 'type-fest'; const color: FixedLengthArray = [255, 128, 64]; // @ts-expect-error color.pop(); //=> Error: Property 'pop' does not exist on type 'FixedLengthArray'. ``` Use-cases: - Declaring fixed-length tuples or arrays with a large number of items. - Creating an array of coordinates with a static length, for example, length of 3 for a 3D vector. @example ``` import type {FixedLengthArray} from 'type-fest'; let color: FixedLengthArray = [255, 128, 64]; const red = color[0]; //=> number const green = color[1]; //=> number const blue = color[2]; //=> number // @ts-expect-error const alpha = color[3]; //=> Error: Property '3' does not exist on type 'FixedLengthArray'. // You can write to valid indices. color[0] = 128; color[1] = 64; color[2] = 32; // But you cannot write to out-of-bounds indices. // @ts-expect-error color[3] = 0.5; //=> Error: Property '3' does not exist on type 'FixedLengthArray'. // @ts-expect-error color.push(0.5); //=> Error: Property 'push' does not exist on type 'FixedLengthArray'. // @ts-expect-error color = [0, 128, 255, 0.5]; //=> Error: Type '[number, number, number, number]' is not assignable to type 'FixedLengthArray'. Types of property 'length' are incompatible. // @ts-expect-error color.length = 4; //=> Error: Cannot assign to 'length' because it is a read-only property. function toHex([r, g, b]: readonly [number, number, number]) { return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`; } console.log(toHex(color)); // `FixedLengthArray` is assignable to `readonly [number, number, number]`. ``` @category Array */ export declare type FixedLengthArray = Except, ArrayLengthMutationKeys | number | 'length'> & {readonly length: Length} & (number extends Length ? {[n: number]: Element} : {}); /** Replaces square-bracketed dot notation with dots, for example, `foo[0].bar` -> `foo.0.bar`. */ declare type FixPathSquareBrackets = Path extends `[${infer Head}]${infer Tail}` ? Tail extends `[${string}` ? `${Head}.${FixPathSquareBrackets}` : `${Head}${FixPathSquareBrackets}` : Path extends `${infer Head}[${infer Middle}]${infer Tail}` ? `${Head}.${FixPathSquareBrackets<`[${Middle}]${Tail}`>}` : Path; /** A `number` that is not an integer. Use-case: Validating and documenting parameters. It does not accept `Infinity`. @example ``` import type {Float} from 'type-fest'; declare function setPercentage(length: Float): void; ``` @see {@link Integer} @category Numeric */ export declare type Float = T extends unknown // To distributive type ? IsFloat extends true ? T : never : never; /** Get a deeply-nested property from an object using a key path, like Lodash's `.get()` function. Use-case: Retrieve a property from deep inside an API response or some other complex object. @example ``` import type {Get} from 'type-fest'; declare function get(object: BaseType, path: Path): Get; type ApiResponse = { hits: { hits: Array<{ _id: string; _source: { name: Array<{ given: string[]; family: string; }>; birthDate: string; }; }>; }; }; const getName = (apiResponse: ApiResponse) => get(apiResponse, 'hits.hits[0]._source.name'); //=> (apiResponse: ApiResponse) => {given: string[]; family: string}[] | undefined // Path also supports a readonly array of strings const getNameWithPathArray = (apiResponse: ApiResponse) => get(apiResponse, ['hits', 'hits', '0', '_source', 'name']); //=> (apiResponse: ApiResponse) => {given: string[]; family: string}[] | undefined // Non-strict mode: type A = Get; //=> string type B = Get, 'foo', {strict: true}>; // => string | undefined ``` @category Object @category Array @category Template literal */ export declare type Get< BaseType, Path extends | readonly string[] | _LiteralStringUnion | Paths>>, Options extends GetOptions = {}, > = GetWithPath< BaseType, Path extends string ? ToPath : Path, ApplyDefaultOptions >; export declare type GetOptions = { /** Include `undefined` in the return type when accessing properties. Setting this to `false` is not recommended. @default true */ strict?: boolean; }; /** Given a type and a tag name, returns the metadata associated with that tag on that type. In the example below, one could use `Tagged` to represent "a string that is valid JSON". That type might be useful -- for instance, it communicates that the value can be safely passed to `JSON.parse` without it throwing an exception. However, it doesn't indicate what type of value will be produced on parse (which is sometimes known). `JsonOf` solves this; it represents "a string that is valid JSON and that, if parsed, would produce a value of type T". The type T is held in the metadata associated with the `'JSON'` tag. This article explains more about [how tag metadata works and when it can be useful](https://medium.com/@ethanresnick/advanced-typescript-tagged-types-improved-with-type-level-metadata-5072fc125fcf). @example ``` import type {Tagged, GetTagMetadata} from 'type-fest'; type JsonOf = Tagged; function stringify(it: T) { return JSON.stringify(it) as JsonOf; } function parse>(it: T) { return JSON.parse(it) as GetTagMetadata; } const x = stringify({hello: 'world'}); const parsed = parse(x); // The type of `parsed` is { hello: string } ``` @category Type */ export declare type GetTagMetadata, TagName extends PropertyKey> = Type[typeof tag][TagName]; /** Like the `Get` type but receives an array of strings as a path parameter. */ declare type GetWithPath> = Keys extends readonly [] ? BaseType : Keys extends readonly [infer Head, ...infer Tail] ? GetWithPath< PropertyOf, Options>, Extract, Options > : never; /** Declare locally scoped properties on `globalThis`. When defining a global variable in a declaration file is inappropriate, it can be helpful to define a `type` or `interface` (say `ExtraGlobals`) with the global variable and then cast `globalThis` via code like `globalThis as unknown as ExtraGlobals`. Instead of casting through `unknown`, you can update your `type` or `interface` to extend `GlobalThis` and then directly cast `globalThis`. @example ``` import type {GlobalThis} from 'type-fest'; type ExtraGlobals = GlobalThis & { readonly GLOBAL_TOKEN: string; }; const globalToken = (globalThis as ExtraGlobals).GLOBAL_TOKEN; //=> string ``` @category Type */ export declare type GlobalThis = typeof globalThis; /** Returns a boolean for whether a given number is greater than another number. @example ``` import type {GreaterThan} from 'type-fest'; type A = GreaterThan<1, -5>; //=> true type B = GreaterThan<1, 1>; //=> false type C = GreaterThan<1, 5>; //=> false ``` */ export declare type GreaterThan = A extends number // For distributing `A` ? B extends number // For distributing `B` ? number extends A | B ? never : [ IsEqual, IsEqual, IsEqual, IsEqual, ] extends infer R extends [boolean, boolean, boolean, boolean] ? Or< And, IsEqual>, And, IsEqual> > extends true ? true : Or< And, IsEqual>, And, IsEqual> > extends true ? false : true extends R[number] ? false : [IsNegative, IsNegative] extends infer R extends [boolean, boolean] ? [true, false] extends R ? false : [false, true] extends R ? true : [false, false] extends R ? PositiveNumericStringGt<`${A}`, `${B}`> : PositiveNumericStringGt<`${NumberAbsolute}`, `${NumberAbsolute}`> : never : never : never // Should never happen : never; /** Returns a boolean for whether a given number is greater than or equal to another number. @example ``` import type {GreaterThanOrEqual} from 'type-fest'; type A = GreaterThanOrEqual<1, -5>; //=> true type B = GreaterThanOrEqual<1, 1>; //=> true type C = GreaterThanOrEqual<1, 5>; //=> false ``` */ export declare type GreaterThanOrEqual = number extends A | B ? never : A extends number // For distributing `A` ? B extends number // For distributing `B` ? A extends B ? true : GreaterThan : never // Should never happen : never; /** Test if the given function has multiple call signatures. Needed to handle the case of a single call signature with properties. Multiple call signatures cannot currently be supported due to a TypeScript limitation. @see https://github.com/microsoft/TypeScript/issues/29732 */ declare type HasMultipleCallSignatures unknown> = T extends {(...arguments_: infer A): unknown; (...arguments_: infer B): unknown} ? B extends A ? A extends B ? false : true : true : false; /** Creates a type that represents `true` or `false` depending on whether the given type has any optional fields. This is useful when you want to create an API whose behavior depends on the presence or absence of optional fields. @example ``` import type {HasOptionalKeys, OptionalKeysOf} from 'type-fest'; type UpdateService = { removeField: HasOptionalKeys extends true ? (field: OptionalKeysOf) => Promise : never; }; ``` @category Utilities */ export declare type HasOptionalKeys = OptionalKeysOf extends never ? false : true; /** Creates a type that represents `true` or `false` depending on whether the given type has any readonly fields. This is useful when you want to create an API whose behavior depends on the presence or absence of readonly fields. @example ``` import type {HasReadonlyKeys, ReadonlyKeysOf} from 'type-fest'; type UpdateService = { removeField: HasReadonlyKeys extends true ? (field: ReadonlyKeysOf) => Promise : never; }; ``` @category Utilities */ export declare type HasReadonlyKeys = ReadonlyKeysOf extends never ? false : true; /** Creates a type that represents `true` or `false` depending on whether the given type has any required fields. This is useful when you want to create an API whose behavior depends on the presence or absence of required fields. @example ``` import type {HasRequiredKeys} from 'type-fest'; type GeneratorOptions