/** * 类型工具库。 * * @packageDocumentation */ import type { BuildTuple } from './internal'; import type { BuiltIns } from './internal'; import type { HasMultipleCallSignatures } from './internal'; import type { HomomorphicPick } from './internal'; import type { IfArrayReadonly } from './internal'; import type { IsLowerCase } from './internal'; import type { IsNumberLike } from './internal'; import type { IsNumeric } from './internal'; import type { IsUpperCase } from './internal'; import type { NonRecursiveType } from './internal'; import type { Not } from './internal'; import type { NumberAbsolute } from './internal'; import type { PositiveNumericStringGt } from './internal'; import type { RequireNone } from './internal'; import type { StaticPartOfArray } from './internal'; import type { StringToNumber } from './internal'; import type { ToString } from './internal'; import type { TupleMax } from './internal'; import type { TupleMin } from './internal'; import type { UpperCaseCharacters } from './internal'; import type { VariablePartOfArray } from './internal'; import type { WordSeparators } from './internal'; /** 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'; And; //=> true And; //=> false ``` @see {@link Or} */ declare type And = [A, B][number] extends true ? true : true extends [IsEqual, IsEqual][number] ? false : never; declare type AnyArray_2 = Array | ReadonlyArray; export { AnyArray_2 as AnyArray } /** * 任意异步函数。 * * @public */ export declare type AnyAsyncFunction = Record & { (...args: any[]): Promise; }; /** * 任意函数。 * * @public */ declare type AnyFunction_2 = Record & { (...args: any[]): any; }; export { AnyFunction_2 as AnyFunction } /** * 任意对象。 * * @public */ declare type AnyObject_2 = Record; export { AnyObject_2 as AnyObject } /** Methods to exclude. */ declare type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'; declare type AsyncFunction = (...arguments_: any[]) => Promise; /** 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. function getFooSync(someArg: SomeType): Foo { // … } type AsyncifiedFooGetter = Asyncify; //=> type AsyncifiedFooGetter = (someArg: SomeType) => Promise; // Same as `getFooSync` but asynchronous. const getFooAsync: AsyncifiedFooGetter = (someArg) => { // TypeScript now knows that `someArg` is `SomeType` automatically. // It also knows that this function must return `Promise`. // If you have `@typescript-eslint/promise-function-async` linter rule enabled, it will even report that "Functions that return promises must be async.". // … } ``` @category Async */ export declare type Asyncify any> = SetReturnType>>>; /** Useful as a return type in interfaces or abstract classes with missing implementation */ export declare type AsyncOrSync = PromiseLike | T; /** 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'; import {asyncFunction} from 'api'; // This type resolves to the unwrapped return type of `asyncFunction`. type Value = AsyncReturnType; async function doSomething(value: Value) {} asyncFunction().then(value => doSomething(value)); ``` @category Async */ export declare type AsyncReturnType = Awaited>; /** Combination of DeepPartial and DeepWritable */ export declare type Buildable = PartialDeep>; declare type Builtin = Primitive_2 | Function | Date | Error | RegExp; /** Matches any primitive, `void`, `Date`, or `RegExp` value. */ declare type BuiltIns_2 = 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'; // Advanced type CamelCasedProperties = { [K in keyof T as CamelCase]: T[K] }; interface 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>> : Type; /** Convert an array of words to camel-case. */ declare type CamelCaseFromArray< Words extends string[], Options extends CamelCaseOptions, 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} */ declare type CamelCaseOptions = { /** Whether to preserved consecutive uppercase letter. @default true */ 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; }; /** Recursively simplifies a type while including and/or excluding certain types from being simplified. This type is **experimental** and was introduced as a result of this {@link https://github.com/sindresorhus/type-fest/issues/436 issue}. It should be used with caution. See {@link ConditionalSimplify} for usages and examples. @internal @experimental @category Object */ declare type ConditionalSimplifyDeep = Type extends ExcludeType ? Type : Type extends IncludeType ? {[TypeKey in keyof Type]: ConditionalSimplifyDeep} : Type; /** Convert a string literal to screaming-snake-case. This can be useful when, for example, converting a camel-cased object property to a screaming-snake-cased SQL column name. @example ``` import type {ScreamingSnakeCase} from 'type-fest'; const someVariable: ScreamingSnakeCase<'fooBar'> = 'FOO_BAR'; ``` @category Change case @category Template literal */ export declare type ConstantCase = Value extends string ? IsScreamingSnakeCase extends true ? Value : Uppercase> : Value; declare type DeepOmitModify = | { [K in keyof T]: T[K] extends never ? any : T[K] extends object ? DeepOmitModify : never; } | Array> | Promise> | Set> | ReadonlySet> | WeakSet> | Map> | WeakMap>; declare type DefaultPathsOptions = { maxRecursionDepth: 10; bracketNotation: false; leavesOnly: false; depth: number; }; /** * 去除类型 T 中的 undefined。 * * @public * @example * ```typescript * type X = string | undefined * type Y = Defined // => string * ``` */ export declare type Defined = Exclude; /** 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 KebabCase @see SnakeCase @example ``` import type {DelimiterCase} from 'type-fest'; // Simple const someVariable: DelimiterCase<'fooBar', '#'> = 'foo#bar'; // Advanced type OddlyCasedProperties = { [K in keyof T as DelimiterCase]: T[K] }; interface 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 = string extends Value ? Value : Value extends string ? StringArrayToDelimiterCase< SplitIncludingDelimiters, true, WordSeparators, UpperCaseCharacters, Delimiter > : Value; export declare type DotPath = object extends T ? string : T extends any[] ? '0' | SubKeys : T extends readonly any[] ? Extract | SubKeys> : T extends object ? Extract | SubKeys> : never; export declare type DotPathValue = Path extends '0' ? T[0] : Path extends keyof T ? T[Path] : Path extends `${infer K}.${infer R}` ? K extends '0' ? DotPathValue : K extends keyof T ? DotPathValue : unknown : unknown; export declare type DotPathWithRoot = DotPath | '.'; export declare type DotPathWithRootValue = Path extends '.' ? T : DotPathValue; /** Easily extract the type of a given array's elements */ export declare type ElementOf = T extends readonly (infer ET)[] ? ET : never; /** 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 const bar2: EmptyObject = 42; // Fail const bar3: EmptyObject = []; // Fail 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 */ declare type EmptyObject = {[emptyObjectSymbol]?: never}; declare const emptyObjectSymbol: unique symbol; /** 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} const fooWithoutA: FooWithoutA = {a: 1, b: '2'}; //=> errors: 'a' does not exist in type '{ b: string; }' type FooWithoutB = Except; //=> {a: number} & Partial> 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; //=> type PostPayload = { [x: string]: string; [x: number]: string; } // In situations like this, `Except` works better. // It simply removes the `email` key while preserving all the other keys. type PostPayload = Except; //=> type PostPayload = { [x: string]: string; name: string; role: 'admin' | 'user'; } ``` @category Object */ declare type Except = { [KeyType in keyof ObjectType as Filter]: ObjectType[KeyType]; } & (Options['requireExactProps'] extends true ? Partial> : {}); 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; }; declare type ExcludeUndefined = Exclude; /** 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); /** 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; /** * 返回函数 T 第一个参数的类型。 * * @public * @example * ```typescript * type F = (x: string, y: number) => any * type X = FirstParameter // => string * ``` */ export declare type FirstParameter any> = Head>; /** Create a type that represents an array of the given type and length. The array's length and the `Array` prototype methods that manipulate its length are excluded in the resulting type. Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similar type built into TypeScript. Use-cases: - Declaring fixed-length tuples or arrays with a large number of items. - Creating a range union (for example, `0 | 1 | 2 | 3 | 4` from the keys of such a type) without having to resort to recursive types. - Creating an array of coordinates with a static length, for example, length of 3 for a 3D vector. Note: This type does not prevent out-of-bounds access. Prefer `ReadonlyTuple` unless you need mutability. @example ``` import type {FixedLengthArray} from 'type-fest'; type FencingTeam = FixedLengthArray; const guestFencingTeam: FencingTeam = ['Josh', 'Michael', 'Robert']; const homeFencingTeam: FencingTeam = ['George', 'John']; //=> error TS2322: Type string[] is not assignable to type 'FencingTeam' guestFencingTeam.push('Sam'); //=> error TS2339: Property 'push' does not exist on type 'FencingTeam' ``` @category Array @see ReadonlyTuple */ export declare type FixedLengthArray = Pick< ArrayPrototype, Exclude > & { [index: number]: Element; [Symbol.iterator]: () => IterableIterator; readonly length: Length; }; /** Returns a boolean for whether a given number is greater than another number. @example ``` import type {GreaterThan} from 'type-fest'; GreaterThan<1, -5>; //=> true GreaterThan<1, 1>; //=> false GreaterThan<1, 5>; //=> false ``` */ declare type GreaterThan = 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; /** Returns a boolean for whether a given number is greater than or equal to another number. @example ``` import type {GreaterThanOrEqual} from 'type-fest'; GreaterThanOrEqual<1, -5>; //=> true GreaterThanOrEqual<1, 1>; //=> true GreaterThanOrEqual<1, 5>; //=> false ``` */ declare type GreaterThanOrEqual = number extends A | B ? never : A extends B ? true : GreaterThan; /** Functional programming essentials */ export declare type Head = T["length"] extends 0 ? never : T[0]; /** Returns a boolean for whether the given array includes the given item. This can be useful if another type wants to make a decision based on whether the array includes that item. @example ``` import type {Includes} from 'type-fest'; type hasRed = Includes; ``` @category Array */ declare type Includes = Value extends readonly [Value[0], ...infer rest] ? IsEqual extends true ? true : Includes : false; /** A `number` that is an integer. Use-case: Validating and documenting parameters. @example ``` type Integer = Integer<1>; //=> 1 type IntegerWithDecimal = Integer<1.0>; //=> 1 type NegativeInteger = Integer<-1>; //=> -1 type Float = Integer<1.5>; //=> never // Supports non-decimal numbers type OctalInteger: Integer<0o10>; //=> 0o10 type BinaryInteger: Integer<0b10>; //=> 0b10 type HexadecimalInteger: Integer<0x10>; //=> 0x10 ``` @example ``` import type {Integer} from 'type-fest'; declare function setYear(length: Integer): void; ``` @see NegativeInteger @see NonNegativeInteger @category Numeric */ // `${bigint}` is a type that matches a valid bigint literal without the `n` (ex. 1, 0b1, 0o1, 0x1) // Because T is a number and not a string we can effectively use this to filter out any numbers containing decimal points export declare type Integer = T extends unknown // To distributive type ? IsInteger extends true ? T : never : never; declare type InternalPaths> = Options['maxRecursionDepth'] extends infer MaxDepth extends number ? Required extends infer T ? T extends EmptyObject | readonly [] ? never : { [Key in keyof T]: Key extends string | number // Limit `Key` to string or number. ? ( Options['bracketNotation'] extends true ? IsNumberLike extends true ? `[${Key}]` : (Key | ToString) : never | Options['bracketNotation'] extends false // If `Key` is a number, return `Key | `${Key}``, because both `array[0]` and `array['0']` work. ? (Key | ToString) : never ) extends infer TranformedKey extends string | number ? // 1. If style is 'a[0].b' and 'Key' is a numberlike value like 3 or '3', transform 'Key' to `[${Key}]`, else to `${Key}` | Key // 2. If style is 'a.0.b', transform 'Key' to `${Key}` | Key | ((Options['leavesOnly'] extends true ? MaxDepth extends 0 ? TranformedKey : T[Key] extends EmptyObject | readonly [] | NonRecursiveType | ReadonlyMap | ReadonlySet ? TranformedKey : never : TranformedKey ) extends infer _TransformedKey // If `depth` is provided, the condition becomes truthy only when it reaches `0`. // Otherwise, since `depth` defaults to `number`, the condition is always truthy, returning paths at all depths. ? 0 extends Options['depth'] ? _TransformedKey : never : never) | ( // Recursively generate paths for the current key GreaterThan extends true // Limit the depth to prevent infinite recursion ? _Paths; leavesOnly: Options['leavesOnly']; depth: Options['depth'] extends infer Depth extends number // For distributing `Options['depth']` ? Depth extends 0 // Don't subtract further if `Depth` has reached `0` ? never : ToString extends `-${number}` // Don't subtract if `Depth` is -ve ? never : Subtract // If `Subtract` supported -ve numbers, then `depth` could have simply been `Subtract` : never; // Should never happen }> extends infer SubPath ? SubPath extends string | number ? ( Options['bracketNotation'] extends true ? SubPath extends `[${any}]` | `[${any}]${string}` ? `${TranformedKey}${SubPath}` // If next node is number key like `[3]`, no need to add `.` before it. : `${TranformedKey}.${SubPath}` : never ) | ( Options['bracketNotation'] extends false ? `${TranformedKey}.${SubPath}` : never ) : never : never : never ) : never : never }[keyof T & (T extends UnknownArray ? number : unknown)] : never : never; /** * 判断 `T` 是否是 `any` 类型。 * * @public * @see https://stackoverflow.com/a/49928360 * @example * ```typescript * type X = IsAny * // => true * ``` */ export declare type IsAny = 0 extends 1 & T ? true : false; /** 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>(obj: O, key: K) { return obj[key]; } const typedA = get(typedObject, 'a'); //=> 1 const anyA = get(anyObject, 'a'); //=> any ``` @category Type Guard @category Utilities */ declare type IsAny_2 = 0 extends 1 & NoInfer_2 ? true : false; /** * 判断 `T` 是否是空数组。 * * @public * @example * ```typescript * type X = IsEmptyArray<[]> * // => true * ``` */ export declare type IsEmptyArray = T extends any[] ? T extends NonEmptyArray ? false : true : false; /** * 判断 `T` 是否是空对象。 * * @public * @example * ```typescript * type X = IsEmptyObject<{}> * // => true * ``` */ export declare type IsEmptyObject = T extends Object ? IsNever : false; /** 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 */ declare type IsEqual = (() => G extends A & G | G ? 1 : 2) extends (() => G extends B & G | G ? 1 : 2) ? true : false; declare type IsEqualConsideringWritability = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; /** Returns a boolean for whether the given number is a float, like `1.5` or `-1.5`. It returns `false` for `Infinity`. Use-case: - If you want to make a conditional branch based on the result of whether a number is a float or not. @example ``` type Float = IsFloat<1.5>; //=> true type IntegerWithDecimal = IsInteger<1.0>; //=> false type NegativeFloat = IsInteger<-1.5>; //=> true type Infinity_ = IsInteger; //=> false ``` */ declare type IsFloat = T extends number ? `${T}` extends `${infer _Sign extends '' | '-'}${number}.${infer Decimal extends number}` ? Decimal extends Zero ? false : true : false : false; declare type IsFullyWritable = IsEqualConsideringWritability< { [Q in keyof T]: T[Q]; }, Writable< { [Q in keyof T]: T[Q]; } > >; /** Returns a boolean for whether the given number is a integer, like `-5`, `1.0` or `100`. Like [`Number#IsInteger()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/IsInteger) but for types. Use-case: - If you want to make a conditional branch based on the result of whether a number is a intrger or not. @example ``` type Integer = IsInteger<1>; //=> true type IntegerWithDecimal = IsInteger<1.0>; //=> true type NegativeInteger = IsInteger<-1>; //=> true type Float = IsInteger<1.5>; //=> false // Supports non-decimal numbers type OctalInteger: IsInteger<0o10>; //=> true type BinaryInteger: IsInteger<0b10>; //=> true type HexadecimalInteger: IsInteger<0x10>; //=> true ``` */ declare type IsInteger = T extends bigint ? true : T extends number ? number extends T ? false : T extends PositiveInfinity | NegativeInfinity ? false : Not> : false; /** Returns a boolean for whether the given number is a negative number. @see Negative @example ``` import type {IsNegative} from 'type-fest'; type ShouldBeFalse = IsNegative<1>; type ShouldBeTrue = IsNegative<-1>; ``` @category Numeric */ declare type IsNegative = T extends Negative ? true : false; /** * 判断 `T` 是否是 `never` 类型。 * * @public * @example * ```typescript * type X = IsNever * // => true * ``` */ export declare type IsNever = [T] extends [never] ? true : false; /** Returns a boolean for whether the given type is `never`. @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919 @link https://stackoverflow.com/a/53984913/10292952 @link https://www.zhenghao.io/posts/ts-never Useful in type utilities, such as checking if something does not occur. @example ``` import type {IsNever, And} from 'type-fest'; // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts type AreStringsEqual = And< IsNever> extends true ? true : false, IsNever> extends true ? true : false >; type EndIfEqual = AreStringsEqual extends true ? never : void; function endIfEqual(input: I, output: O): EndIfEqual { if (input === output) { process.exit(0); } } endIfEqual('abc', 'abc'); //=> never endIfEqual('abc', '123'); //=> void ``` @category Type Guard @category Utilities */ declare type IsNever_2 = [T] extends [never] ? true : false; /** Returns a boolean for whether the given type is `null`. @example ``` import type {IsNull} from 'type-fest'; type NonNullFallback = IsNull extends true ? Fallback : T; type Example1 = NonNullFallback; //=> string type Example2 = NonNullFallback; //=? number ``` @category Type Guard @category Utilities */ declare type IsNull = [T] extends [null] ? true : false; /** Returns a boolean for whether the string is screaming snake case. */ declare type IsScreamingSnakeCase = Value extends Uppercase ? Includes, '_'>, '_'> extends true ? true : false : false; declare type IsTuple = T extends [infer A] ? T : T extends [infer A, infer B] ? T : T extends [infer A, infer B, infer C] ? T : T extends [infer A, infer B, infer C, infer D] ? T : T extends [infer A, infer B, infer C, infer D, infer E] ? T : never; /** Returns a boolean for whether the given type is `unknown`. @link https://github.com/dsherret/conditional-type-checks/pull/16 Useful in type utilities, such as when dealing with unknown data from API calls. @example ``` import type {IsUnknown} from 'type-fest'; // https://github.com/pajecawav/tiny-global-store/blob/master/src/index.ts type Action = IsUnknown extends true ? (state: TState) => TState, : (state: TState, payload: TPayload) => TState; class Store { constructor(private state: TState) {} execute(action: Action, payload?: TPayload): TState { this.state = action(this.state, payload); return this.state; } // ... other methods } const store = new Store({value: 1}); declare const someExternalData: unknown; store.execute(state => ({value: state.value + 1})); //=> `TPayload` is `void` store.execute((state, payload) => ({value: state.value + payload}), 5); //=> `TPayload` is `5` store.execute((state, payload) => ({value: state.value + payload}), someExternalData); //=> Errors: `action` is `(state: TState) => TState` ``` @category Utilities */ declare type IsUnknown = ( unknown extends T // `T` can be `unknown` or `any` ? IsNull extends false // `any` can be `null`, but `unknown` can't be ? true : false : false ); /** Matches a JSON array. @category JSON */ export declare type JsonArray = JsonValue[] | readonly JsonValue[]; /** Matches a JSON object. This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. @category JSON */ export declare type JsonObject = {[Key in string]: JsonValue} & {[Key in string]?: JsonValue | undefined}; /** Matches any valid JSON primitive value. @category JSON */ declare type JsonPrimitive = string | number | boolean | null; /** Matches any valid JSON value. @see `Jsonify` if you need to transform a type to one that is assignable to `JsonValue`. @category JSON */ export declare type JsonValue = JsonPrimitive | JsonObject | JsonArray; /** Convert a string literal to kebab-case. This can be useful when, for example, converting a camel-cased object property to a kebab-cased CSS class name or a command-line flag. @example ``` import type {KebabCase} from 'type-fest'; // Simple const someVariable: KebabCase<'fooBar'> = 'foo-bar'; // Advanced type KebabCasedProperties = { [K in keyof T as KebabCase]: T[K] }; interface CliOptions { dryRun: boolean; includeFile: string; foo: number; } const rawCliOptions: KebabCasedProperties = { 'dry-run': true, 'include-file': 'bar.js', foo: 123 }; ``` @category Change case @category Template literal */ export declare type KebabCase = DelimiterCase; /** Returns the last element of a union type. @example ``` type Last = LastOfUnion<1 | 2 | 3>; //=> 3 ``` */ declare type LastOfUnion = UnionToIntersection T : never> extends () => (infer R) ? R : never; /** Returns a boolean for whether a given number is less than another number. @example ``` import type {LessThan} from 'type-fest'; LessThan<1, -5>; //=> false LessThan<1, 1>; //=> false LessThan<1, 5>; //=> true ``` */ declare type LessThan = number extends A | B ? never : GreaterThanOrEqual extends true ? false : true; /** Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals. This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore. @example ``` import type {LiteralUnion} from 'type-fest'; // Before type Pet = 'dog' | 'cat' | string; const pet: Pet = ''; // Start typing in your TypeScript-enabled IDE. // You **will not** get auto-completion for `dog` and `cat` literals. // After type Pet2 = LiteralUnion<'dog' | 'cat', string>; const pet: Pet2 = ''; // You **will** get auto-completion for `dog` and `cat` literals. ``` @category Type */ export declare type LiteralUnion< LiteralType, BaseType extends Primitive, > = LiteralType | (BaseType & Record); /** Merge 2 types, properties types from the latter override the ones defined on the former type */ export declare type Merge = Omit & N; /** A negative `number`/`bigint` (`-∞ < x < 0`) Use-case: Validating and documenting parameters. @see NegativeInteger @see NonNegative @category Numeric */ export declare type Negative = T extends Zero ? never : `${T}` extends `-${string}` ? T : never; /** Matches the hidden `-Infinity` type. Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript. @see PositiveInfinity @category Numeric */ // See https://github.com/microsoft/TypeScript/issues/31752 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision export declare type NegativeInfinity = -1e999; /** A negative (`-∞ < x < 0`) `number` that is an integer. Equivalent to `Negative>`. You can't pass a `bigint` as they are already guaranteed to be integers, instead use `Negative`. Use-case: Validating and documenting parameters. @see Negative @see Integer @category Numeric */ export declare type NegativeInteger = Negative>; declare type NoInfer_2 = T extends infer U ? U : never; /** * 非空数组类型。 * * @public * @example * ```typescript * type X = NonEmptyArray * const x: X = [] // => error * ``` */ export declare type NonEmptyArray = [T, ...T[]]; /** A non-negative `number`/`bigint` (`0 <= x < ∞`). Use-case: Validating and documenting parameters. @see NonNegativeInteger @see Negative @example ``` import type {NonNegative} from 'type-fest'; declare function setLength(length: NonNegative): void; ``` @category Numeric */ export declare type NonNegative = T extends Zero ? T : Negative extends never ? T : never; /** A non-negative (`0 <= x < ∞`) `number` that is an integer. Equivalent to `NonNegative>`. You can't pass a `bigint` as they are already guaranteed to be integers, instead use `NonNegative`. Use-case: Validating and documenting parameters. @see NonNegative @see Integer @example ``` import type {NonNegativeInteger} from 'type-fest'; declare function setLength(length: NonNegativeInteger): void; ``` @category Numeric */ export declare type NonNegativeInteger = NonNegative>; /** Like NonNullable but recursive */ export declare type NonNullableDeep = T extends Builtin ? NonNullable : T extends Map ? Map, NonNullableDeep> : T extends ReadonlyMap ? ReadonlyMap, NonNullableDeep> : T extends WeakMap ? WeakMap, NonNullableDeep> : T extends Set ? Set> : T extends ReadonlySet ? ReadonlySet> : T extends WeakSet ? WeakSet> : T extends Promise ? Promise> : T extends {} ? { [K in keyof T]: NonNullableDeep; } : NonNullable; /** Matches non-recursive types. */ declare type NonRecursiveType_2 = BuiltIns_2 | Function | (new (...arguments_: any[]) => unknown); export declare type Nullable = T | null | undefined; /** Recursive nullable */ export declare type NullableDeep = T extends Builtin ? T | null : T extends Map ? Map, NullableDeep> : T extends WeakMap ? WeakMap, NullableDeep> : T extends Set ? Set> : T extends WeakSet ? WeakSet> : T extends Array ? T extends IsTuple ? { [K in keyof T]: NullableDeep | null; } : Array> : T extends Promise ? Promise> : T extends {} ? { [K in keyof T]: NullableDeep; } : T | null; declare type Numeric = number | bigint; /** Omit all properties of given type in object type */ export declare type OmitBy = Pick< T, { [K in keyof T]: T[K] extends P ? never : K; }[keyof T] >; /** Recursively omit deep properties */ export declare type OmitDeep, Filter> = T extends Builtin ? T : T extends Map ? ValueType extends DeepOmitModify ? Map> : T : T extends ReadonlyMap ? ValueType extends DeepOmitModify ? ReadonlyMap> : T : T extends WeakMap ? ValueType extends DeepOmitModify ? WeakMap> : T : T extends Set ? ItemType extends DeepOmitModify ? Set> : T : T extends ReadonlySet ? ItemType extends DeepOmitModify ? ReadonlySet> : T : T extends WeakSet ? ItemType extends DeepOmitModify ? WeakSet> : T : T extends Array ? ItemType extends DeepOmitModify ? Array> : T : T extends Promise ? ItemType extends DeepOmitModify ? Promise> : T : { [K in Exclude, keyof Filter>]+?: T[K]; } & OmitBy< { [K in Extract, keyof Filter>]+?: Filter[K] extends true ? never : T[K] extends DeepOmitModify ? OmitDeep : T[K]; }, never > & { [K in Exclude, keyof Filter>]: T[K]; } & OmitBy< { [K in Extract, keyof Filter>]: Filter[K] extends true ? never : T[K] extends DeepOmitModify ? OmitDeep : T[K]; }, never >; /** Similar to the builtin Omit, but checks the filter strictly. */ export declare type OmitStrict = Pick>; /** * 同 `T | T[]`。 * * @public * @example * ```typescript * type X = OneOrMore // => number | number[] * ``` */ export declare type OneOrMore = T | T[]; /** Gets keys of an object which are optional */ export declare type OptionalKeys = { [K in keyof T]-?: undefined extends { [K2 in keyof T]: K2; }[K] ? K : never; }[keyof T]; /** Extract all optional keys from the given type. This is useful when you want to create a new type that contains different type values for the optional keys only. @example ``` import type {OptionalKeysOf, Except} from 'type-fest'; interface User { name: string; surname: string; luckyNumber?: number; } const REMOVE_FIELD = Symbol('remove field symbol'); type UpdateOperation = 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 */ declare type OptionalKeysOf = Exclude<{ [Key in keyof BaseType]: BaseType extends Record ? never : Key }[keyof BaseType], undefined>; /** Returns a boolean for whether either of two given types are true. Use-case: Constructing complex conditional types where multiple conditions must be satisfied. @example ``` import type {Or} from 'type-fest'; Or; //=> true Or; //=> false ``` @see {@link And} */ declare type Or = [A, B][number] extends false ? false : true extends [IsEqual, IsEqual][number] ? true : never; export declare namespace PackageJson { /** A person who has been involved in creating or maintaining the package. */ export type Person = | string | { name: string; url?: string; email?: string; }; export type BugsLocation = | string | { /** The URL to the package's issue tracker. */ url?: string; /** The email address to which issues should be reported. */ email?: string; }; export type DirectoryLocations = { [directoryType: string]: JsonValue | undefined; /** Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder. */ bin?: string; /** Location for Markdown files. */ doc?: string; /** Location for example scripts. */ example?: string; /** Location for the bulk of the library. */ lib?: string; /** Location for man pages. Sugar to generate a `man` array by walking the folder. */ man?: string; /** Location for test files. */ test?: string; }; export type Scripts = { /** Run **before** the package is published (Also run on local `npm install` without any arguments). */ prepublish?: string; /** Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`. */ prepare?: string; /** Run **before** the package is prepared and packed, **only** on `npm publish`. */ prepublishOnly?: string; /** Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies). */ prepack?: string; /** Run **after** the tarball has been generated and moved to its final destination. */ postpack?: string; /** Run **after** the package is published. */ publish?: string; /** Run **after** the package is published. */ postpublish?: string; /** Run **before** the package is installed. */ preinstall?: string; /** Run **after** the package is installed. */ install?: string; /** Run **after** the package is installed and after `install`. */ postinstall?: string; /** Run **before** the package is uninstalled and before `uninstall`. */ preuninstall?: string; /** Run **before** the package is uninstalled. */ uninstall?: string; /** Run **after** the package is uninstalled. */ postuninstall?: string; /** Run **before** bump the package version and before `version`. */ preversion?: string; /** Run **before** bump the package version. */ version?: string; /** Run **after** bump the package version. */ postversion?: string; /** Run with the `npm test` command, before `test`. */ pretest?: string; /** Run with the `npm test` command. */ test?: string; /** Run with the `npm test` command, after `test`. */ posttest?: string; /** Run with the `npm stop` command, before `stop`. */ prestop?: string; /** Run with the `npm stop` command. */ stop?: string; /** Run with the `npm stop` command, after `stop`. */ poststop?: string; /** Run with the `npm start` command, before `start`. */ prestart?: string; /** Run with the `npm start` command. */ start?: string; /** Run with the `npm start` command, after `start`. */ poststart?: string; /** Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. */ prerestart?: string; /** Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. */ restart?: string; /** Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. */ postrestart?: string; } & Partial>; /** Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL. */ export type Dependency = Partial>; /** A mapping of conditions and the paths to which they resolve. */ export type ExportConditions = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style [condition: string]: Exports; }; /** Entry points of a module, optionally with conditions and subpath exports. */ export type Exports = | null | string | Array | ExportConditions; /** Import map entries of a module, optionally with conditions and subpath imports. */ export type Imports = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style [key: `#${string}`]: Exports; }; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export interface NonStandardEntryPoints { /** An ECMAScript module ID that is the primary entry point to the program. */ module?: string; /** A module ID with untranspiled code that is the primary entry point to the program. */ esnext?: | string | { [moduleName: string]: string | undefined; main?: string; browser?: string; }; /** A hint to JavaScript bundlers or component tools when packaging modules for client side use. */ browser?: | string | Partial>; /** Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. [Read more.](https://webpack.js.org/guides/tree-shaking/) */ sideEffects?: boolean | string[]; } export type TypeScriptConfiguration = { /** Location of the bundled TypeScript declaration file. */ types?: string; /** Version selection map of TypeScript. */ typesVersions?: Partial>>>; /** Location of the bundled TypeScript declaration file. Alias of `types`. */ typings?: string; }; /** An alternative configuration for workspaces. */ export type WorkspaceConfig = { /** An array of workspace pattern strings which contain the workspace packages. */ packages?: WorkspacePattern[]; /** Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns. [Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn. [Not supported](https://github.com/npm/rfcs/issues/287) by npm. */ nohoist?: WorkspacePattern[]; }; /** A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process. The patterns are handled with [minimatch](https://github.com/isaacs/minimatch). @example `docs` → Include the docs directory and install its dependencies. `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`. */ export type WorkspacePattern = string; export type YarnConfiguration = { /** If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`. Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line. */ flat?: boolean; /** Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file. */ resolutions?: Dependency; }; export type JSPMConfiguration = { /** JSPM configuration. */ jspm?: PackageJson; }; /** Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. */ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export interface PackageJsonStandard { /** The name of the package. */ name?: string; /** Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). */ version?: string; /** Package description, listed in `npm search`. */ description?: string; /** Keywords associated with package, listed in `npm search`. */ keywords?: string[]; /** The URL to the package's homepage. */ homepage?: LiteralUnion<'.', string>; /** The URL to the package's issue tracker and/or the email address to which issues should be reported. */ bugs?: BugsLocation; /** The license for the package. */ license?: string; /** The licenses for the package. */ licenses?: Array<{ type?: string; url?: string; }>; author?: Person; /** A list of people who contributed to the package. */ contributors?: Person[]; /** A list of people who maintain the package. */ maintainers?: Person[]; /** The files included in the package. */ files?: string[]; /** Resolution algorithm for importing ".js" files from the package's scope. [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) */ type?: 'module' | 'commonjs'; /** The module ID that is the primary entry point to the program. */ main?: string; /** Subpath exports to define entry points of the package. [Read more.](https://nodejs.org/api/packages.html#subpath-exports) */ exports?: Exports; /** Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself. [Read more.](https://nodejs.org/api/packages.html#subpath-imports) */ imports?: Imports; /** The executable files that should be installed into the `PATH`. */ bin?: | string | Partial>; /** Filenames to put in place for the `man` program to find. */ man?: string | string[]; /** Indicates the structure of the package. */ directories?: DirectoryLocations; /** Location for the code repository. */ repository?: | string | { type: string; url: string; /** Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo). [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md) */ directory?: string; }; /** Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. */ scripts?: Scripts; /** Is used to set configuration parameters used in package scripts that persist across upgrades. */ config?: JsonObject; /** The dependencies of the package. */ dependencies?: Dependency; /** Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. */ devDependencies?: Dependency; /** Dependencies that are skipped if they fail to install. */ optionalDependencies?: Dependency; /** Dependencies that will usually be required by the package user directly or via another dependency. */ peerDependencies?: Dependency; /** Indicate peer dependencies that are optional. */ peerDependenciesMeta?: Partial>; /** Package names that are bundled when the package is published. */ bundledDependencies?: string[]; /** Alias of `bundledDependencies`. */ bundleDependencies?: string[]; /** Engines that this package runs on. */ engines?: { [EngineName in 'npm' | 'node' | string]?: string; }; /** @deprecated */ engineStrict?: boolean; /** Operating systems the module runs on. */ os?: Array>; /** CPU architectures the module runs on. */ cpu?: Array>; /** If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. @deprecated */ preferGlobal?: boolean; /** If set to `true`, then npm will refuse to publish it. */ private?: boolean; /** A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. */ publishConfig?: PublishConfig; /** Describes and notifies consumers of a package's monetary support information. [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md) */ funding?: string | { /** The type of funding. */ type?: LiteralUnion< | 'github' | 'opencollective' | 'patreon' | 'individual' | 'foundation' | 'corporation', string >; /** The URL to the funding page. */ url: string; }; /** Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/). Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run your install command once in order to install all of them in a single pass. Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces. */ workspaces?: WorkspacePattern[] | WorkspaceConfig; } /** Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions). */ export type NodeJsStandard = { /** Defines which package manager is expected to be used when working on the current project. It can set to any of the [supported package managers](https://nodejs.org/api/corepack.html#supported-package-managers), and will ensure that your teams use the exact same package manager versions without having to install anything else than Node.js. __This field is currently experimental and needs to be opted-in; check the [Corepack](https://nodejs.org/api/corepack.html) page for details about the procedure.__ @example ```json { "packageManager": "@" } ``` */ packageManager?: string; }; export type PublishConfig = { /** Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig). */ [additionalProperties: string]: JsonValue | undefined; /** When publishing scoped packages, the access level defaults to restricted. If you want your scoped package to be publicly viewable (and installable) set `--access=public`. The only valid values for access are public and restricted. Unscoped packages always have an access level of public. */ access?: 'public' | 'restricted'; /** The base URL of the npm registry. Default: `'https://registry.npmjs.org/'` */ registry?: string; /** The tag to publish the package under. Default: `'latest'` */ tag?: string; }; } /** Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. @category File */ export declare type PackageJson = JsonObject & PackageJson.NodeJsStandard & PackageJson.PackageJsonStandard & PackageJson.NonStandardEntryPoints & PackageJson.TypeScriptConfiguration & PackageJson.YarnConfiguration & PackageJson.JSPMConfiguration; /** Mark some properties as optional, leaving others unchanged */ export declare type PartialBy = Omit & Partial>; /** Like Partial but recursive */ export declare type PartialDeep = T extends Builtin ? T : T extends Map ? Map, PartialDeep> : T extends ReadonlyMap ? ReadonlyMap, PartialDeep> : T extends WeakMap ? WeakMap, PartialDeep> : T extends Set ? Set> : T extends ReadonlySet ? ReadonlySet> : T extends WeakSet ? WeakSet> : T extends Array ? T extends IsTuple ? { [K in keyof T]?: PartialDeep; } : Array> : T extends Promise ? Promise> : T extends {} ? { [K in keyof T]?: PartialDeep; } : Partial; export declare type PartialDeepBy> = IsAny_2 extends true ? SimplifyDeep> : PartialDeepByHelper>; declare type PartialDeepByHelper = KeyPathsTuple extends [infer KeyPath, ...infer RestPaths] ? PartialDeepByHelper, RestPaths> : BaseType; declare type PartialDeepBySinglePath = BaseType extends NonRecursiveType_2 ? BaseType : KeyPath extends `${infer Property}.${infer RestPath}` ? { [Key in keyof BaseType]: Property extends `${Key & (string | number)}` ? PartialDeepBySinglePath : BaseType[Key]; } : SetOptional) & keyof BaseType>; /** Converts a string literal to pascal-case. @example ``` import type {PascalCase} from 'type-fest'; // Simple const someVariable: PascalCase<'foo-bar'> = 'FooBar'; // Advanced type PascalCaseProps = { [K in keyof T as PascalCase]: T[K] }; interface RawOptions { 'dry-run': boolean; 'full_family_name': string; foo: number; } const dbResult: CamelCasedProperties = { DryRun: true, FullFamilyName: 'bar.js', Foo: 123 }; ``` @category Change case @category Template literal */ export declare type PascalCase = CamelCase extends string ? Capitalize> : CamelCase; /** * 获取对象的路径。最多支持 7 级路径。 * * @deprecated 使用 `DotPath` 代替 */ export declare type Path = string | string[]; /** Generate a union of all possible paths to properties in the given object. It also works with arrays. Use-case: You want a type-safe way to access deeply nested properties in an object. @example ``` import type {Paths} from 'type-fest'; type Project = { filename: string; listA: string[]; listB: [{filename: string}]; folder: { subfolder: { filename: string; }; }; }; type ProjectPaths = Paths; //=> 'filename' | 'listA' | 'listB' | 'folder' | `listA.${number}` | 'listB.0' | 'listB.0.filename' | 'folder.subfolder' | 'folder.subfolder.filename' declare function open(path: Path): void; open('filename'); // Pass open('folder.subfolder'); // Pass open('folder.subfolder.filename'); // Pass open('foo'); // TypeError // Also works with arrays open('listA.1'); // Pass open('listB.0'); // Pass open('listB.1'); // TypeError. Because listB only has one element. ``` @category Object @category Array */ declare type Paths = _Paths; declare type _Paths> = T extends NonRecursiveType | ReadonlyMap | ReadonlySet ? never : IsAny_2 extends true ? never : T extends UnknownArray ? number extends T['length'] // We need to handle the fixed and non-fixed index part of the array separately. ? InternalPaths, Options> | InternalPaths[number]>, Options> : InternalPaths : T extends object ? InternalPaths : never; /** Paths options. @see {@link Paths} */ declare type PathsOptions = { /** The maximum depth to recurse when searching for paths. @default 10 */ maxRecursionDepth?: number; /** Use bracket notation for array indices and numeric object keys. @default false @example ``` type ArrayExample = { array: ['foo']; }; type A = Paths; //=> 'array' | 'array.0' type B = Paths; //=> 'array' | 'array[0]' ``` @example ``` type NumberKeyExample = { 1: ['foo']; }; type A = Paths; //=> 1 | '1' | '1.0' type B = Paths; //=> '[1]' | '[1][0]' ``` */ bracketNotation?: boolean; /** Only include leaf paths in the output. @default false @example ``` type Post = { id: number; author: { id: number; name: { first: string; last: string; }; }; }; type AllPaths = Paths; //=> 'id' | 'author' | 'author.id' | 'author.name' | 'author.name.first' | 'author.name.last' type LeafPaths = Paths; //=> 'id' | 'author.id' | 'author.name.first' | 'author.name.last' ``` @example ``` type ArrayExample = { array: Array<{foo: string}>; tuple: [string, {bar: string}]; }; type AllPaths = Paths; //=> 'array' | `array.${number}` | `array.${number}.foo` | 'tuple' | 'tuple.0' | 'tuple.1' | 'tuple.1.bar' type LeafPaths = Paths; //=> `array.${number}.foo` | 'tuple.0' | 'tuple.1.bar' ``` */ leavesOnly?: boolean; /** Only include paths at the specified depth. By default all paths up to {@link PathsOptions.maxRecursionDepth | `maxRecursionDepth`} are included. Note: Depth starts at `0` for root properties. @default number @example ``` type Post = { id: number; author: { id: number; name: { first: string; last: string; }; }; }; type DepthZero = Paths; //=> 'id' | 'author' type DepthOne = Paths; //=> 'author.id' | 'author.name' type DepthTwo = Paths; //=> 'author.name.first' | 'author.name.last' type LeavesAtDepthOne = Paths; //=> 'author.id' ``` */ depth?: number; }; /** * 获取对象的路径值。最多支持 7 级路径。 * * @deprecated 使用 `DotPathValue` 代替 */ export declare type PathValue = any; /** Pick all properties of given type in object type */ export declare type PickBy = Pick< T, { [K in keyof T]: T[K] extends P ? K : never; }[keyof T] >; /** Matches the hidden `Infinity` type. Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript. @see NegativeInfinity @category Numeric */ // See https://github.com/microsoft/TypeScript/issues/31752 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision export declare type PositiveInfinity = 1e999; /** Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). @category Type */ declare type Primitive = | null | undefined | string | number | boolean | symbol | bigint; /** Essentials */ declare type Primitive_2 = string | number | boolean | bigint | symbol | undefined | null; /** Like Readonly but recursive */ export declare type ReadonlyDeep = T extends Builtin ? T : T extends Map ? ReadonlyMap, ReadonlyDeep> : T extends ReadonlyMap ? ReadonlyMap, ReadonlyDeep> : T extends WeakMap ? WeakMap, ReadonlyDeep> : T extends Set ? ReadonlySet> : T extends ReadonlySet ? ReadonlySet> : T extends WeakSet ? WeakSet> : T extends Promise ? Promise> : T extends {} ? { readonly [K in keyof T]: ReadonlyDeep; } : Readonly; /** Gets keys of an object which are readonly */ export declare type ReadonlyKeys = { [P in keyof T]-?: IsFullyWritable> extends true ? never : P; }[keyof T]; declare type RemoveLastCharacter = Sentence extends `${infer LeftSide}${Character}` ? SkipEmptyWord : never; /** Requires all of the keys in the given object. */ declare type RequireAll = Required>; /** Create a type that requires all of the given keys or none of the given keys. The remaining keys are kept as is. Use-cases: - Creating interfaces for components with mutually-inclusive keys. The caveat with `RequireAllOrNone` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireAllOrNone` can't do anything to prevent extra keys it doesn't know about. @example ``` import type {RequireAllOrNone} from 'type-fest'; type Responder = { text?: () => string; json?: () => string; secure: boolean; }; const responder1: RequireAllOrNone = { secure: true }; const responder2: RequireAllOrNone = { text: () => '{"message": "hi"}', json: () => '{"message": "ok"}', secure: true }; ``` @category Object */ export declare type RequireAllOrNone = ( | RequireAll | RequireNone ) & Omit; /** Create a type that requires at least one of the given keys. The remaining keys are kept as is. @example ``` import type {RequireAtLeastOne} from 'type-fest'; type Responder = { text?: () => string; json?: () => string; secure?: boolean; }; const responder: RequireAtLeastOne = { json: () => '{"message": "ok"}', secure: true }; ``` @category Object */ export declare type RequireAtLeastOne< ObjectType, KeysType extends keyof ObjectType = keyof ObjectType, > = { // For each `Key` in `KeysType` make a mapped type: [Key in KeysType]-?: Required> & // 1. Make `Key`'s type required // 2. Make all other keys in `KeysType` optional Partial>>; }[KeysType] & // 3. Add the remaining keys not in `KeysType` Except; /** Mark some properties as required, leaving others unchanged */ export declare type RequiredBy = Exclude & Required>; /** Like Required but recursive */ export declare type RequiredDeep = T extends Builtin ? NonNullable : T extends Map ? Map, RequiredDeep> : T extends ReadonlyMap ? ReadonlyMap, RequiredDeep> : T extends WeakMap ? WeakMap, RequiredDeep> : T extends Set ? Set> : T extends ReadonlySet ? ReadonlySet> : T extends WeakSet ? WeakSet> : T extends Promise ? Promise> : T extends {} ? { [K in keyof T]-?: RequiredDeep; } : NonNullable; /** Create a type from another type with all keys and nested keys set to required. Use-cases: - Creating optional configuration interfaces where the underlying implementation still requires all options to be fully specified. - Modeling the resulting type after a deep merge with a set of defaults. @example ``` import type {RequiredDeep} from 'type-fest'; type Settings = { textEditor?: { fontSize?: number | undefined; fontColor?: string | undefined; fontWeight?: number | undefined; } autocomplete?: boolean | undefined; autosave?: boolean | undefined; }; type RequiredSettings = RequiredDeep; // type RequiredSettings = { // textEditor: { // fontSize: number; // fontColor: string; // fontWeight: number; // } // autocomplete: boolean; // autosave: boolean; // } ``` Note that types containing overloaded functions are not made deeply required due to a [TypeScript limitation](https://github.com/microsoft/TypeScript/issues/29732). @category Utilities @category Object @category Array @category Set @category Map */ declare type RequiredDeep_2 = ExcludeUndefined> = E extends BuiltIns ? E : E extends Map ? Map, RequiredDeep_2> : E extends Set ? Set> : E extends ReadonlyMap ? ReadonlyMap, RequiredDeep_2> : E extends ReadonlySet ? ReadonlySet> : E extends WeakMap ? WeakMap, RequiredDeep_2> : E extends WeakSet ? WeakSet> : E extends Promise ? Promise> : E extends (...arguments_: any[]) => unknown ? {} extends RequiredObjectDeep ? E : HasMultipleCallSignatures extends true ? E : ((...arguments_: Parameters) => ReturnType) & RequiredObjectDeep : E extends object ? E extends Array // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156 ? ItemType[] extends E // Test for arrays (non-tuples) specifically ? Array> // Recreate relevant array type to prevent eager evaluation of circular reference : RequiredObjectDeep // Tuples behave properly : RequiredObjectDeep : unknown; /** Create a type that makes the given keys required. You can specify deeply nested key paths. The remaining keys are kept as is. Use-case: Selectively make nested properties required in complex types like models. @example ``` import type {SetRequiredDeep} from 'type-fest'; type Foo = { a?: number; b?: string; c?: { d?: number }[] } type SomeRequiredDeep = SetRequiredDeep; // type SomeRequiredDeep = { // a: number; // Is now required // b?: string; // c: { // d: number // Is now required // }[] // } // Set specific indices in an array to be required. type ArrayExample = SetRequiredDeep<{a: [number?, number?, number?]}, 'a.0' | 'a.1'>; //=> {a: [number, number, number?]} ``` @category Object */ export declare type RequiredDeepBy> = IsAny_2 extends true ? SimplifyDeep> : SetRequiredDeepHelper>; /** Gets keys of an object which are required */ export declare type RequiredKeys = Exclude>; declare type RequiredObjectDeep = { [KeyType in keyof ObjectType]-?: RequiredDeep_2 }; /** Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is. Use-cases: - Creating interfaces for components that only need one of the keys to display properly. - Declaring generic keys in a single place for a single use-case that gets narrowed down via `RequireExactlyOne`. The caveat with `RequireExactlyOne` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireExactlyOne` can't do anything to prevent extra keys it doesn't know about. @example ``` import type {RequireExactlyOne} from 'type-fest'; type Responder = { text: () => string; json: () => string; secure: boolean; }; const responder: RequireExactlyOne = { // Adding a `text` key here would cause a compile error. json: () => '{"message": "ok"}', secure: true }; ``` @category Object */ export declare type RequireExactlyOne = {[Key in KeysType]: ( Required> & Partial, never>> )}[KeysType] & Omit; /** Remove the optional modifier from the specified keys in an array. */ declare type SetArrayRequired< TArray extends UnknownArray, Keys, Counter extends any[] = [], Accumulator extends UnknownArray = [], > = TArray extends unknown // For distributing `TArray` when it's a union ? keyof TArray & `${number}` extends never // Exit if `TArray` is empty (e.g., []), or // `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`). ? [...Accumulator, ...TArray] : TArray extends readonly [(infer First)?, ...infer Rest] ? '0' extends OptionalKeysOf // If the first element of `TArray` is optional ? `${Counter['length']}` extends `${Keys & (string | number)}` // If the current index needs to be required ? SetArrayRequired // If the current element is optional, but it doesn't need to be required, // then we can exit early, since no further elements can now be made required. : [...Accumulator, ...TArray] : SetArrayRequired : never // Should never happen, since `[(infer F)?, ...infer R]` is a top-type for arrays. : never; /** Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type. Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional. @example ``` import type {SetOptional} from 'type-fest'; type Foo = { a: number; b?: string; c: boolean; } type SomeOptional = SetOptional; // type SomeOptional = { // a: number; // b?: string; // Was already optional and still is. // c?: boolean; // Is now optional. // } ``` @category Object */ declare type SetOptional = BaseType extends unknown // To distribute `BaseType` when it's a union type. ? Simplify< // Pick just the keys that are readonly from the base type. Except & // Pick the keys that should be mutable from the base type and make them mutable. Partial> > : never; /** Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type. Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required. @example ``` import type {SetRequired} from 'type-fest'; type Foo = { a?: number; b: string; c?: boolean; } type SomeRequired = SetRequired; // type SomeRequired = { // a?: number; // b: string; // Was already required and still is. // c: boolean; // Is now required. // } // Set specific indices in an array to be required. type ArrayExample = SetRequired<[number?, number?, number?], 0 | 1>; //=> [number, number, number?] ``` @category Object */ declare type SetRequired = BaseType extends UnknownArray ? SetArrayRequired extends infer ResultantArray ? IfArrayReadonly, ResultantArray> : never : Simplify< // Pick just the keys that are optional from the base type. Except & // Pick the keys that should be required from the base type and make them required. Required> >; /** Internal helper for {@link SetRequiredDeep}. Recursively transforms the `BaseType` by applying {@link SetRequiredDeepSinglePath} for each path in `KeyPathsTuple`. */ declare type SetRequiredDeepHelper = KeyPathsTuple extends [infer KeyPath, ...infer RestPaths] ? SetRequiredDeepHelper, RestPaths> : BaseType; /** Makes a single path required in `BaseType`. */ declare type SetRequiredDeepSinglePath = BaseType extends NonRecursiveType ? BaseType : KeyPath extends `${infer Property}.${infer RestPath}` ? { [Key in keyof BaseType]: Property extends `${Key & (string | number)}` ? SetRequiredDeepSinglePath : BaseType[Key]; } : SetRequired) & keyof BaseType>; /** Create a function type with a return type of your choice and the same parameters as the given function type. Use-case: You want to define a wrapped function that returns something different while receiving the same parameters. For example, you might want to wrap a function that can throw an error into one that will return `undefined` instead. @example ``` import type {SetReturnType} from 'type-fest'; type MyFunctionThatCanThrow = (foo: SomeType, bar: unknown) => SomeOtherType; type MyWrappedFunction = SetReturnType; //=> type MyWrappedFunction = (foo: SomeType, bar: unknown) => SomeOtherType | undefined; ``` @category Function */ declare type SetReturnType any, TypeToReturn> = // Just using `Parameters` isn't ideal because it doesn't handle the `this` fake parameter. Function_ extends (this: infer ThisArgument, ...arguments_: infer Arguments) => any ? ( // If a function did not specify the `this` fake parameter, it will be inferred to `unknown`. // We want to detect this situation just to display a friendlier type upon hovering on an IntelliSense-powered IDE. IsUnknown extends true ? (...arguments_: Arguments) => TypeToReturn : (this: ThisArgument, ...arguments_: Arguments) => TypeToReturn ) : ( // This part should be unreachable, but we make it meaningful just in case… (...arguments_: Parameters) => TypeToReturn ); /** 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; function fn(object: Record): void {} fn(literal); // Good: literal object type is sealed fn(someType); // Good: type is sealed fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened fn(someInterface as Simplify); // Good: transform an `interface` into a `type` ``` @link https://github.com/microsoft/TypeScript/issues/15300 @see SimplifyDeep @category Object */ export declare type Simplify = {[KeyType in keyof T]: T[KeyType]} & {}; /** Deeply simplifies an object type. You can exclude certain types from being simplified by providing them in the second generic `ExcludeType`. Useful to flatten the type output to improve type hints shown in editors. @example ``` import type {SimplifyDeep} from 'type-fest'; type PositionX = { left: number; right: number; }; type PositionY = { top: number; bottom: number; }; type Properties1 = { height: number; position: PositionY; }; type Properties2 = { width: number; position: PositionX; }; type Properties = Properties1 & Properties2; // In your editor, hovering over `Props` will show the following: // // type Properties = Properties1 & Properties2; type SimplifyDeepProperties = SimplifyDeep; // But if wrapped in SimplifyDeep, hovering over `SimplifyDeepProperties` will show a flattened object with all the properties: // // SimplifyDeepProperties = { // height: number; // width: number; // position: { // top: number; // bottom: number; // left: number; // right: number; // }; // }; ``` @example ``` import type {SimplifyDeep} from 'type-fest'; // A complex type that you don't want or need to simplify type ComplexType = { a: string; b: 'b'; c: number; ... }; type PositionX = { left: number; right: number; }; type PositionY = { top: number; bottom: number; }; // You want to simplify all other types type Properties1 = { height: number; position: PositionY; foo: ComplexType; }; type Properties2 = { width: number; position: PositionX; foo: ComplexType; }; type SimplifyDeepProperties = SimplifyDeep; // If wrapped in `SimplifyDeep` and set `ComplexType` to exclude, hovering over `SimplifyDeepProperties` will // show a flattened object with all the properties except `ComplexType`: // // SimplifyDeepProperties = { // height: number; // width: number; // position: { // top: number; // bottom: number; // left: number; // right: number; // }; // foo: ComplexType; // }; ``` @see Simplify @category Object */ declare type SimplifyDeep = ConditionalSimplifyDeep< Type, ExcludeType | NonRecursiveType | Set | Map, object >; declare type SkipEmptyWord = Word extends '' ? [] : [Word]; /** Convert a string literal to snake-case. This can be useful when, for example, converting a camel-cased object property to a snake-cased SQL column name. @example ``` import type {SnakeCase} from 'type-fest'; // Simple const someVariable: SnakeCase<'fooBar'> = 'foo_bar'; // Advanced type SnakeCasedProperties = { [K in keyof T as SnakeCase]: T[K] }; interface ModelProps { isHappy: boolean; fullFamilyName: string; foo: number; } const dbResult: SnakeCasedProperties = { 'is_happy': true, 'full_family_name': 'Carla Smith', foo: 123 }; ``` @category Change case @category Template literal */ export declare type SnakeCase = DelimiterCase; /** Unlike a simpler split, this one includes the delimiter splitted on in the resulting array literal. This is to enable splitting on, for example, upper-case characters. @category Template literal */ declare type SplitIncludingDelimiters = SplitIncludingDelimiters_, Delimiter>; declare type SplitIncludingDelimiters_ = Source extends '' ? [] : Source extends `${infer FirstPart}${Delimiter}${infer SecondPart}` ? ( Source extends `${FirstPart}${infer UsedDelimiter}${SecondPart}` ? UsedDelimiter extends Delimiter ? Source extends `${infer FirstPart}${UsedDelimiter}${infer SecondPart}` ? [...SplitIncludingDelimiters, UsedDelimiter, ...SplitIncludingDelimiters] : never : never : never ) : [Source]; /** Takes the result of a splitted string literal and recursively concatenates it together into the desired casing. It receives `UsedWordSeparators` and `UsedUpperCaseCharacters` as input to ensure it's fully encapsulated. @see SplitIncludingDelimiters */ declare type StringArrayToDelimiterCase = Parts extends [`${infer FirstPart}`, ...infer RemainingParts] ? `${StringPartToDelimiterCase}${StringArrayToDelimiterCase}` : Parts extends [string] ? string : ''; /** Format a specific part of the splitted string literal that `StringArrayToDelimiterCase<>` fuses together, ensuring desired casing. @see StringArrayToDelimiterCase */ declare type StringPartToDelimiterCase = StringPart extends UsedWordSeparators ? Delimiter : Start extends true ? Lowercase : StringPart extends UsedUpperCaseCharacters ? `${Delimiter}${Lowercase}` : StringPart; /** Converts a numeric string to a number. @example ``` type PositiveInt = StringToNumber<'1234'>; //=> 1234 type NegativeInt = StringToNumber<'-1234'>; //=> -1234 type PositiveFloat = StringToNumber<'1234.56'>; //=> 1234.56 type NegativeFloat = StringToNumber<'-1234.56'>; //=> -1234.56 type PositiveInfinity = StringToNumber<'Infinity'>; //=> Infinity type NegativeInfinity = StringToNumber<'-Infinity'>; //=> -Infinity ``` @category String @category Numeric @category Template literal */ declare type StringToNumber_2 = S extends `${infer N extends number}` ? N : S extends 'Infinity' ? PositiveInfinity : S extends '-Infinity' ? NegativeInfinity : never; declare type SubKeys = K extends keyof T ? `${K}.${DotPath}` : never; /** Returns the difference between two numbers. Note: - A or B can only support `-999` ~ `999`. - If the result is negative, you can only get `number`. @example ``` import type {Subtract} from 'type-fest'; Subtract<333, 222>; //=> 111 Subtract<111, -222>; //=> 333 Subtract<-111, 222>; //=> number Subtract; //=> PositiveInfinity Subtract; //=> number ``` @category Numeric */ // TODO: Support big integer and negative number. declare type Subtract = number extends A | B ? number : [ IsEqual, IsEqual, IsEqual, IsEqual, ] extends infer R extends [boolean, boolean, boolean, boolean] ? Or< And, IsEqual>, And, IsEqual> > extends true ? PositiveInfinity : Or< And, IsEqual>, And, IsEqual> > extends true ? NegativeInfinity : true extends R[number] ? number : [IsNegative, IsNegative] extends infer R ? [false, false] extends R ? BuildTuple extends infer R ? R extends [...BuildTuple, ...infer R] ? R['length'] : number : never : LessThan extends true ? number : [false, true] extends R ? Sum> : Subtract, NumberAbsolute> : never : never; /** Returns the sum of two numbers. Note: - A or B can only support `-999` ~ `999`. - A and B can only be small integers, less than 1000. - If the result is negative, you can only get `number`. @example ``` import type {Sum} from 'type-fest'; Sum<111, 222>; //=> 333 Sum<-111, 222>; //=> 111 Sum<111, -222>; //=> number Sum; //=> PositiveInfinity Sum; //=> number ``` @category Numeric */ // TODO: Support big integer and negative number. declare type Sum = number extends A | B ? number : [ IsEqual, IsEqual, IsEqual, IsEqual, ] extends infer R extends [boolean, boolean, boolean, boolean] ? Or< And, IsEqual>, And, IsEqual> > extends true ? PositiveInfinity : Or< And, IsEqual>, And, IsEqual> > extends true ? NegativeInfinity : true extends R[number] ? number : ([IsNegative, IsNegative] extends infer R ? [false, false] extends R ? [...BuildTuple, ...BuildTuple]['length'] : [true, true] extends R ? number : TupleMax<[NumberAbsolute, NumberAbsolute]> extends infer Max_ ? TupleMin<[NumberAbsolute, NumberAbsolute]> extends infer Min_ extends number ? Max_ extends A | B ? Subtract : number : never : never : never) & number : never; export declare type Tail = T["length"] extends 0 ? never : ((...t: T) => void) extends (first: any, ...rest: infer Rest) => void ? Rest : never; export declare namespace TsConfigJson { export namespace CompilerOptions { export type JSX = | 'preserve' | 'react' | 'react-jsx' | 'react-jsxdev' | 'react-native'; export type Module = | 'CommonJS' | 'AMD' | 'System' | 'UMD' | 'ES6' | 'ES2015' | 'ES2020' | 'ES2022' | 'ESNext' | 'Node16' | 'NodeNext' | 'Preserve' | 'None' // Lowercase alternatives | 'commonjs' | 'amd' | 'system' | 'umd' | 'es6' | 'es2015' | 'es2020' | 'es2022' | 'esnext' | 'node16' | 'nodenext' | 'preserve' | 'none'; export type NewLine = | 'CRLF' | 'LF' // Lowercase alternatives | 'crlf' | 'lf'; export type Target = | 'ES3' | 'ES5' | 'ES6' | 'ES2015' | 'ES2016' | 'ES2017' | 'ES2018' | 'ES2019' | 'ES2020' | 'ES2021' | 'ES2022' | 'ES2023' | 'ES2024' | 'ESNext' // Lowercase alternatives | 'es3' | 'es5' | 'es6' | 'es2015' | 'es2016' | 'es2017' | 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'es2023' | 'es2024' | 'esnext'; // eslint-disable-next-line unicorn/prevent-abbreviations export type Lib = | 'ES5' | 'ES6' | 'ES7' | 'ES2015' | 'ES2015.Collection' | 'ES2015.Core' | 'ES2015.Generator' | 'ES2015.Iterable' | 'ES2015.Promise' | 'ES2015.Proxy' | 'ES2015.Reflect' | 'ES2015.Symbol.WellKnown' | 'ES2015.Symbol' | 'ES2016' | 'ES2016.Array.Include' | 'ES2017' | 'ES2017.ArrayBuffer' | 'ES2017.Date' | 'ES2017.Intl' | 'ES2017.Object' | 'ES2017.SharedMemory' | 'ES2017.String' | 'ES2017.TypedArrays' | 'ES2018' | 'ES2018.AsyncGenerator' | 'ES2018.AsyncIterable' | 'ES2018.Intl' | 'ES2018.Promise' | 'ES2018.Regexp' | 'ES2019' | 'ES2019.Array' | 'ES2019.Object' | 'ES2019.String' | 'ES2019.Symbol' | 'ES2020' | 'ES2020.BigInt' | 'ES2020.Promise' | 'ES2020.String' | 'ES2020.Symbol.WellKnown' | 'ES2020.SharedMemory' | 'ES2020.Intl' | 'ES2021' | 'ES2021.Intl' | 'ES2021.Promise' | 'ES2021.String' | 'ES2021.WeakRef' | 'ES2022' | 'ES2022.Array' | 'ES2022.Error' | 'ES2022.Intl' | 'ES2022.Object' | 'ES2022.RegExp' | 'ES2022.String' | 'ES2023' | 'ES2023.Array' | 'ES2023.Collection' | 'ES2023.Intl' | 'ES2024' | 'ES2024.ArrayBuffer' | 'ES2024.Collection' | 'ES2024.Object' | 'ES2024.Promise' | 'ES2024.Regexp' | 'ES2024.SharedMemory' | 'ES2024.String' | 'ESNext' | 'ESNext.Array' | 'ESNext.AsyncIterable' | 'ESNext.BigInt' | 'ESNext.Collection' | 'ESNext.Decorators' | 'ESNext.Disposable' | 'ESNext.Intl' | 'ESNext.Iterator' | 'ESNext.Promise' | 'ESNext.String' | 'ESNext.Symbol' | 'ESNext.WeakRef' | 'DOM' | 'DOM.Iterable' | 'ScriptHost' | 'WebWorker' | 'WebWorker.AsyncIterable' | 'WebWorker.ImportScripts' | 'WebWorker.Iterable' // Lowercase alternatives | 'es5' | 'es6' | 'es7' | 'es2015' | 'es2015.collection' | 'es2015.core' | 'es2015.generator' | 'es2015.iterable' | 'es2015.promise' | 'es2015.proxy' | 'es2015.reflect' | 'es2015.symbol.wellknown' | 'es2015.symbol' | 'es2016' | 'es2016.array.include' | 'es2017' | 'es2017.arraybuffer' | 'es2017.date' | 'es2017.intl' | 'es2017.object' | 'es2017.sharedmemory' | 'es2017.string' | 'es2017.typedarrays' | 'es2018' | 'es2018.asyncgenerator' | 'es2018.asynciterable' | 'es2018.intl' | 'es2018.promise' | 'es2018.regexp' | 'es2019' | 'es2019.array' | 'es2019.object' | 'es2019.string' | 'es2019.symbol' | 'es2020' | 'es2020.bigint' | 'es2020.promise' | 'es2020.string' | 'es2020.symbol.wellknown' | 'es2020.sharedmemory' | 'es2020.intl' | 'es2021' | 'es2021.intl' | 'es2021.promise' | 'es2021.string' | 'es2021.weakref' | 'es2022' | 'es2022.array' | 'es2022.error' | 'es2022.intl' | 'es2022.object' | 'es2022.regexp' | 'es2022.string' | 'es2023' | 'es2023.array' | 'es2023.collection' | 'es2023.intl' | 'es2024' | 'es2024.arraybuffer' | 'es2024.collection' | 'es2024.object' | 'es2024.promise' | 'es2024.regexp' | 'es2024.sharedmemory' | 'es2024.string' | 'esnext' | 'esnext.array' | 'esnext.asynciterable' | 'esnext.bigint' | 'esnext.collection' | 'esnext.decorators' | 'esnext.disposable' | 'esnext.intl' | 'esnext.iterator' | 'esnext.promise' | 'esnext.string' | 'esnext.symbol' | 'esnext.weakref' | 'dom' | 'dom.iterable' | 'scripthost' | 'webworker' | 'webworker.asynciterable' | 'webworker.importscripts' | 'webworker.iterable'; export type Plugin = { /** Plugin name. */ name: string; }; export type ImportsNotUsedAsValues = | 'remove' | 'preserve' | 'error'; export type FallbackPolling = | 'fixedPollingInterval' | 'priorityPollingInterval' | 'dynamicPriorityPolling' | 'fixedInterval' | 'priorityInterval' | 'dynamicPriority' | 'fixedChunkSize'; export type WatchDirectory = | 'useFsEvents' | 'fixedPollingInterval' | 'dynamicPriorityPolling' | 'fixedChunkSizePolling'; export type WatchFile = | 'fixedPollingInterval' | 'priorityPollingInterval' | 'dynamicPriorityPolling' | 'useFsEvents' | 'useFsEventsOnParentDirectory' | 'fixedChunkSizePolling'; export type ModuleResolution = | 'classic' | 'node' | 'node10' | 'node16' | 'nodenext' | 'bundler' // Pascal-cased alternatives | 'Classic' | 'Node' | 'Node10' | 'Node16' | 'NodeNext' | 'Bundler'; export type ModuleDetection = | 'auto' | 'legacy' | 'force'; export type IgnoreDeprecations = '5.0'; } export type CompilerOptions = { /** The character set of the input files. @default 'utf8' @deprecated This option will be removed in TypeScript 5.5. */ charset?: string; /** Enables building for project references. @default true */ composite?: boolean; /** Generates corresponding d.ts files. @default false */ declaration?: boolean; /** Specify output directory for generated declaration files. */ declarationDir?: string; /** Show diagnostic information. @default false */ diagnostics?: boolean; /** Reduce the number of projects loaded automatically by TypeScript. @default false */ disableReferencedProjectLoad?: boolean; /** Enforces using indexed accessors for keys declared using an indexed type. @default false */ noPropertyAccessFromIndexSignature?: boolean; /** Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. @default false */ emitBOM?: boolean; /** Only emit `.d.ts` declaration files. @default false */ emitDeclarationOnly?: boolean; /** Differentiate between undefined and not present when type checking. @default false */ exactOptionalPropertyTypes?: boolean; /** Enable incremental compilation. @default `composite` */ incremental?: boolean; /** Specify file to store incremental compilation information. @default '.tsbuildinfo' */ tsBuildInfoFile?: string; /** Emit a single file with source maps instead of having a separate file. @default false */ inlineSourceMap?: boolean; /** Emit the source alongside the sourcemaps within a single file. Requires `--inlineSourceMap` to be set. @default false */ inlineSources?: boolean; /** Specify what JSX code is generated. @default 'preserve' */ jsx?: CompilerOptions.JSX; /** Specifies the object invoked for `createElement` and `__spread` when targeting `'react'` JSX emit. @default 'React' */ reactNamespace?: string; /** Specify the JSX factory function to use when targeting React JSX emit, e.g. `React.createElement` or `h`. @default 'React.createElement' */ jsxFactory?: string; /** Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. @default 'React.Fragment' */ jsxFragmentFactory?: string; /** Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`. @default 'react' */ jsxImportSource?: string; /** Print names of files part of the compilation. @default false */ listFiles?: boolean; /** Specifies the location where debugger should locate map files instead of generated locations. */ mapRoot?: string; /** Specify module code generation: 'None', 'CommonJS', 'AMD', 'System', 'UMD', 'ES6', 'ES2015' or 'ESNext'. Only 'AMD' and 'System' can be used in conjunction with `--outFile`. 'ES6' and 'ES2015' values may be used when targeting 'ES5' or lower. @default ['ES3', 'ES5'].includes(target) ? 'CommonJS' : 'ES6' */ module?: CompilerOptions.Module; /** Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6). @default ['AMD', 'System', 'ES6'].includes(module) ? 'classic' : 'node' */ moduleResolution?: CompilerOptions.ModuleResolution; /** Specifies the end of line sequence to be used when emitting files: 'crlf' (Windows) or 'lf' (Unix). @default 'LF' */ newLine?: CompilerOptions.NewLine; /** Disable full type checking (only critical parse and emit errors will be reported). @default false */ noCheck?: boolean; /** Do not emit output. @default false */ noEmit?: boolean; /** Do not generate custom helper functions like `__extends` in compiled output. @default false */ noEmitHelpers?: boolean; /** Do not emit outputs if any type checking errors were reported. @default false */ noEmitOnError?: boolean; /** Warn on expressions and declarations with an implied 'any' type. @default false */ noImplicitAny?: boolean; /** Raise error on 'this' expressions with an implied any type. @default false */ noImplicitThis?: boolean; /** Report errors on unused locals. @default false */ noUnusedLocals?: boolean; /** Report errors on unused parameters. @default false */ noUnusedParameters?: boolean; /** Do not include the default library file (lib.d.ts). @default false */ noLib?: boolean; /** Do not add triple-slash references or module import targets to the list of compiled files. @default false */ noResolve?: boolean; /** Disable strict checking of generic signatures in function types. @default false @deprecated This option will be removed in TypeScript 5.5. */ noStrictGenericChecks?: boolean; /** @deprecated use `skipLibCheck` instead. */ skipDefaultLibCheck?: boolean; /** Skip type checking of declaration files. @default false */ skipLibCheck?: boolean; /** Concatenate and emit output to single file. */ outFile?: string; /** Redirect output structure to the directory. */ outDir?: string; /** Do not erase const enum declarations in generated code. @default false */ preserveConstEnums?: boolean; /** Do not resolve symlinks to their real path; treat a symlinked file like a real one. @default false */ preserveSymlinks?: boolean; /** Keep outdated console output in watch mode instead of clearing the screen. @default false */ preserveWatchOutput?: boolean; /** Stylize errors and messages using color and context (experimental). @default true // Unless piping to another program or redirecting output to a file. */ pretty?: boolean; /** Do not emit comments to output. @default false */ removeComments?: boolean; /** Specifies the root directory of input files. Use to control the output directory structure with `--outDir`. */ rootDir?: string; /** Unconditionally emit imports for unresolved files. @default false */ isolatedModules?: boolean; /** Require sufficient annotation on exports so other tools can trivially generate declaration files. @default false */ isolatedDeclarations?: boolean; /** Generates corresponding '.map' file. @default false */ sourceMap?: boolean; /** Specifies the location where debugger should locate TypeScript files instead of source locations. */ sourceRoot?: string; /** Suppress excess property checks for object literals. @default false @deprecated This option will be removed in TypeScript 5.5. */ suppressExcessPropertyErrors?: boolean; /** Suppress noImplicitAny errors for indexing objects lacking index signatures. @default false @deprecated This option will be removed in TypeScript 5.5. */ suppressImplicitAnyIndexErrors?: boolean; /** Do not emit declarations for code that has an `@internal` annotation. */ stripInternal?: boolean; /** Specify ECMAScript target version. @default 'es3' */ target?: CompilerOptions.Target; /** Default catch clause variables as `unknown` instead of `any`. @default false */ useUnknownInCatchVariables?: boolean; /** Watch input files. @default false @deprecated Use watchOptions instead. */ watch?: boolean; /** Specify the polling strategy to use when the system runs out of or doesn't support native file watchers. @deprecated Use watchOptions.fallbackPolling instead. */ fallbackPolling?: CompilerOptions.FallbackPolling; /** Specify the strategy for watching directories under systems that lack recursive file-watching functionality. @default 'useFsEvents' @deprecated Use watchOptions.watchDirectory instead. */ watchDirectory?: CompilerOptions.WatchDirectory; /** Specify the strategy for watching individual files. @default 'useFsEvents' @deprecated Use watchOptions.watchFile instead. */ watchFile?: CompilerOptions.WatchFile; /** Enables experimental support for ES7 decorators. @default false */ experimentalDecorators?: boolean; /** Emit design-type metadata for decorated declarations in source. @default false */ emitDecoratorMetadata?: boolean; /** Do not report errors on unused labels. @default false */ allowUnusedLabels?: boolean; /** Report error when not all code paths in function return a value. @default false */ noImplicitReturns?: boolean; /** Add `undefined` to a type when accessed using an index. @default false */ noUncheckedIndexedAccess?: boolean; /** Report error if failed to find a source file for a side effect import. @default false */ noUncheckedSideEffectImports?: boolean; /** Report errors for fallthrough cases in switch statement. @default false */ noFallthroughCasesInSwitch?: boolean; /** Ensure overriding members in derived classes are marked with an override modifier. @default false */ noImplicitOverride?: boolean; /** Do not report errors on unreachable code. @default false */ allowUnreachableCode?: boolean; /** Disallow inconsistently-cased references to the same file. @default true */ forceConsistentCasingInFileNames?: boolean; /** Emit a v8 CPU profile of the compiler run for debugging. @default 'profile.cpuprofile' */ generateCpuProfile?: string; /** Generates an event trace and a list of types. */ generateTrace?: boolean; /** Base directory to resolve non-relative module names. */ baseUrl?: string; /** Specify path mapping to be computed relative to baseUrl option. */ paths?: Record; /** List of TypeScript language server plugins to load. */ plugins?: CompilerOptions.Plugin[]; /** Specify list of root directories to be used when resolving modules. */ rootDirs?: string[]; /** Specify list of directories for type definition files to be included. */ typeRoots?: string[]; /** Type declaration files to be included in compilation. */ types?: string[]; /** Enable tracing of the name resolution process. @default false */ traceResolution?: boolean; /** Allow javascript files to be compiled. @default false */ allowJs?: boolean; /** Do not truncate error messages. @default false */ noErrorTruncation?: boolean; /** Allow default imports from modules with no default export. This does not affect code emit, just typechecking. @default module === 'system' || esModuleInterop */ allowSyntheticDefaultImports?: boolean; /** Do not emit `'use strict'` directives in module output. @default false @deprecated This option will be removed in TypeScript 5.5. */ noImplicitUseStrict?: boolean; /** Enable to list all emitted files. @default false */ listEmittedFiles?: boolean; /** Disable size limit for JavaScript project. @default false */ disableSizeLimit?: boolean; /** List of library files to be included in the compilation. */ lib?: CompilerOptions.Lib[]; /** Enable strict null checks. @default false */ strictNullChecks?: boolean; /** The maximum dependency depth to search under `node_modules` and load JavaScript files. Only applicable with `--allowJs`. @default 0 */ maxNodeModuleJsDepth?: number; /** Import emit helpers (e.g. `__extends`, `__rest`, etc..) from tslib. @default false */ importHelpers?: boolean; /** Specify emit/checking behavior for imports that are only used for types. @default 'remove' @deprecated Use `verbatimModuleSyntax` instead. */ importsNotUsedAsValues?: CompilerOptions.ImportsNotUsedAsValues; /** Parse in strict mode and emit `'use strict'` for each source file. @default false */ alwaysStrict?: boolean; /** Enable all strict type checking options. @default false */ strict?: boolean; /** Enable stricter checking of of the `bind`, `call`, and `apply` methods on functions. @default false */ strictBindCallApply?: boolean; /** Provide full support for iterables in `for-of`, spread, and destructuring when targeting `ES5` or `ES3`. @default false */ downlevelIteration?: boolean; /** Report errors in `.js` files. @default false */ checkJs?: boolean; /** Built-in iterators are instantiated with a `TReturn` type of undefined instead of `any`. @default false */ strictBuiltinIteratorReturn?: boolean; /** Disable bivariant parameter checking for function types. @default false */ strictFunctionTypes?: boolean; /** Ensure non-undefined class properties are initialized in the constructor. @default false */ strictPropertyInitialization?: boolean; /** Emit `__importStar` and `__importDefault` helpers for runtime Babel ecosystem compatibility and enable `--allowSyntheticDefaultImports` for typesystem compatibility. @default false */ esModuleInterop?: boolean; /** Allow accessing UMD globals from modules. @default false */ allowUmdGlobalAccess?: boolean; /** Resolve `keyof` to string valued property names only (no numbers or symbols). @default false @deprecated This option will be removed in TypeScript 5.5. */ keyofStringsOnly?: boolean; /** Emit ECMAScript standard class fields. @default false */ useDefineForClassFields?: boolean; /** Generates a sourcemap for each corresponding `.d.ts` file. @default false */ declarationMap?: boolean; /** Include modules imported with `.json` extension. @default false */ resolveJsonModule?: boolean; /** Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it. @default false */ assumeChangesOnlyAffectDirectDependencies?: boolean; /** Output more detailed compiler performance information after building. @default false */ extendedDiagnostics?: boolean; /** Print names of files that are part of the compilation and then stop processing. @default false */ listFilesOnly?: boolean; /** Disable preferring source files instead of declaration files when referencing composite projects. @default true if composite, false otherwise */ disableSourceOfProjectReferenceRedirect?: boolean; /** Opt a project out of multi-project reference checking when editing. @default false */ disableSolutionSearching?: boolean; /** Print names of files which TypeScript sees as a part of your project and the reason they are part of the compilation. @default false */ explainFiles?: boolean; /** Preserve unused imported values in the JavaScript output that would otherwise be removed. @default true @deprecated Use `verbatimModuleSyntax` instead. */ preserveValueImports?: boolean; /** List of file name suffixes to search when resolving a module. */ moduleSuffixes?: string[]; /** Control what method is used to detect module-format JS files. @default 'auto' */ moduleDetection?: CompilerOptions.ModuleDetection; /** Allows TypeScript files to import each other with a TypeScript-specific extension like .ts, .mts, or .tsx. @default false */ allowImportingTsExtensions?: boolean; /** Forces TypeScript to consult the exports field of package.json files if it ever reads from a package in node_modules. @default false */ resolvePackageJsonExports?: boolean; /** Forces TypeScript to consult the imports field of package.json files when performing a lookup that starts with # from a file whose ancestor directory contains a package.json. @default false */ resolvePackageJsonImports?: boolean; /** Suppress errors for file formats that TypeScript does not understand. @default false */ allowArbitraryExtensions?: boolean; /** List of additional conditions that should succeed when TypeScript resolves from package.json. */ customConditions?: string[]; /** Anything that uses the type modifier is dropped entirely. @default false */ verbatimModuleSyntax?: boolean; /** Suppress deprecation warnings */ ignoreDeprecations?: CompilerOptions.IgnoreDeprecations; }; export namespace WatchOptions { export type WatchFileKind = | 'FixedPollingInterval' | 'PriorityPollingInterval' | 'DynamicPriorityPolling' | 'FixedChunkSizePolling' | 'UseFsEvents' | 'UseFsEventsOnParentDirectory'; export type WatchDirectoryKind = | 'UseFsEvents' | 'FixedPollingInterval' | 'DynamicPriorityPolling' | 'FixedChunkSizePolling'; export type PollingWatchKind = | 'FixedInterval' | 'PriorityInterval' | 'DynamicPriority' | 'FixedChunkSize'; } export type WatchOptions = { /** Specify the strategy for watching individual files. @default 'UseFsEvents' */ watchFile?: WatchOptions.WatchFileKind | Lowercase; /** Specify the strategy for watching directories under systems that lack recursive file-watching functionality. @default 'UseFsEvents' */ watchDirectory?: WatchOptions.WatchDirectoryKind | Lowercase; /** Specify the polling strategy to use when the system runs out of or doesn't support native file watchers. */ fallbackPolling?: WatchOptions.PollingWatchKind | Lowercase; /** Enable synchronous updates on directory watchers for platforms that don't support recursive watching natively. */ synchronousWatchDirectory?: boolean; /** Specifies a list of directories to exclude from watch */ excludeDirectories?: string[]; /** Specifies a list of files to exclude from watch */ excludeFiles?: string[]; }; /** Auto type (.d.ts) acquisition options for this project. */ export type TypeAcquisition = { /** Enable auto type acquisition. */ enable?: boolean; /** Specifies a list of type declarations to be included in auto type acquisition. For example, `['jquery', 'lodash']`. */ include?: string[]; /** Specifies a list of type declarations to be excluded from auto type acquisition. For example, `['jquery', 'lodash']`. */ exclude?: string[]; /** Disable infering what types should be added based on filenames in a project. */ disableFilenameBasedTypeAcquisition?: boolean; }; export type References = { /** A normalized path on disk. */ path: string; /** The path as the user originally wrote it. */ originalPath?: string; /** True if the output of this reference should be prepended to the output of this project. Only valid for `--outFile` compilations. @deprecated This option will be removed in TypeScript 5.5. */ prepend?: boolean; /** True if it is intended that this reference form a circularity. */ circular?: boolean; }; } /** Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 3.7). @category File */ export declare type TsConfigJson = { /** Instructs the TypeScript compiler how to compile `.ts` files. */ compilerOptions?: TsConfigJson.CompilerOptions; /** Instructs the TypeScript compiler how to watch files. */ watchOptions?: TsConfigJson.WatchOptions; /** Auto type (.d.ts) acquisition options for this project. */ typeAcquisition?: TsConfigJson.TypeAcquisition; /** Enable Compile-on-Save for this project. */ compileOnSave?: boolean; /** Path to base configuration file to inherit from. */ extends?: string | string[]; /** If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. When a `files` property is specified, only those files and those specified by `include` are included. */ files?: string[]; /** Specifies a list of files to be excluded from compilation. The `exclude` property only affects the files included via the `include` property and not the `files` property. Glob patterns require TypeScript version 2.0 or later. */ exclude?: string[]; /** Specifies a list of glob patterns that match files to be included in compilation. If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. */ include?: string[]; /** Referenced projects. */ references?: TsConfigJson.References[]; }; /** 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}; ``` A more applicable example which could make its way into your library code follows. @example ``` import type {UnionToIntersection} from 'type-fest'; class CommandOne { commands: { a1: () => undefined, b1: () => undefined, } } class CommandTwo { commands: { a2: (argA: string) => undefined, b2: (argB: string) => undefined, } } const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands); type Union = typeof union; //=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void} type Intersection = UnionToIntersection; //=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void} ``` @category Type */ export declare 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 allow indexing by the resulting type ? Intersection & Union : never; /** Convert a union type into an unordered tuple type of its elements. "Unordered" means the elements of the tuple are not guaranteed to be in the same order as in the union type. The arrangement can appear random and may change at any time. This can be useful when you have objects with a finite set of keys and want a type defining only the allowed keys, but do not want to repeat yourself. @example ``` import type {UnionToTuple} from 'type-fest'; type Numbers = 1 | 2 | 3; type NumbersTuple = UnionToTuple; //=> [1, 2, 3] ``` @example ``` import type {UnionToTuple} from 'type-fest'; const pets = { dog: '🐶', cat: '🐱', snake: '🐍', }; type Pet = keyof typeof pets; //=> 'dog' | 'cat' | 'snake' const petList = Object.keys(pets) as UnionToTuple; //=> ['dog', 'cat', 'snake'] ``` @category Array */ export declare type UnionToTuple> = IsNever_2 extends false ? [...UnionToTuple>, L] : []; /** 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 */ declare type UnknownArray = readonly unknown[]; declare type UpperCaseToLowerCase = T extends Uppercase ? Lowercase : T; /** Easily extract the type of a given object's values */ export declare type ValueOf = T[keyof T]; /** Mark some properties which only the former including as optional and set the value to never */ declare type Without = { [P in Exclude]?: never; }; /** Split a string (almost) like Lodash's `_.words()` function. - Split on each word that begins with a capital letter. - Split on each {@link WordSeparators}. - Split on numeric sequence. @example ``` import type {Words} from 'type-fest'; type Words0 = Words<'helloWorld'>; //=> ['hello', 'World'] type Words1 = Words<'helloWORLD'>; //=> ['hello', 'WORLD'] type Words2 = Words<'hello-world'>; //=> ['hello', 'world'] type Words3 = Words<'--hello the_world'>; //=> ['hello', 'the', 'world'] type Words4 = Words<'lifeIs42'>; //=> ['life', 'Is', '42'] ``` @category Change case @category Template literal */ declare type Words< Sentence extends string, LastCharacter extends string = '', CurrentWord extends string = '', > = Sentence extends `${infer FirstCharacter}${infer RemainingCharacters}` ? FirstCharacter extends WordSeparators // Skip word separator ? [...SkipEmptyWord, ...Words] : LastCharacter extends '' // Fist char of word ? Words // Case change: non-numeric to numeric, push word : [false, true] extends [IsNumeric, IsNumeric] ? [...SkipEmptyWord, ...Words] // Case change: numeric to non-numeric, push word : [true, false] extends [IsNumeric, IsNumeric] ? [...SkipEmptyWord, ...Words] // No case change: concat word : [true, true] extends [IsNumeric, IsNumeric] ? Words // Case change: lower to upper, push word : [true, true] extends [IsLowerCase, IsUpperCase] ? [...SkipEmptyWord, ...Words] // Case change: upper to lower, brings back the last character, push word : [true, true] extends [IsUpperCase, IsLowerCase] ? [...RemoveLastCharacter, ...Words] // No case change: concat word : Words : [...SkipEmptyWord]; /** Make readonly object writable */ export declare type Writable = { -readonly [P in keyof T]: T[P]; }; /** Like Writable but recursive */ export declare type WritableDeep = T extends Builtin ? T : T extends Map ? Map, WritableDeep> : T extends ReadonlyMap ? Map, WritableDeep> : T extends WeakMap ? WeakMap, WritableDeep> : T extends Set ? Set> : T extends ReadonlySet ? Set> : T extends WeakSet ? WeakSet> : T extends Promise ? Promise> : T extends {} ? { -readonly [K in keyof T]: WritableDeep; } : T; /** Gets keys of an object which are writable */ export declare type WritableKeys = { [P in keyof T]-?: IsFullyWritable> extends true ? P : never; }[keyof T]; /** get the XOR type which could make 2 types exclude each other */ export declare type XOR = T | U extends object ? (Without & U) | (Without & T) : T | U; declare type Zero = 0 | 0n; export { }