This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

95
node_modules/type-fest/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,95 @@
// Basic
export * from './source/primitive';
export * from './source/typed-array';
export * from './source/basic';
export * from './source/observable-like';
// Utilities
export {Except} from './source/except';
export {Mutable} from './source/mutable';
export {Writable} from './source/writable';
export {Merge} from './source/merge';
export {MergeExclusive} from './source/merge-exclusive';
export {RequireAtLeastOne} from './source/require-at-least-one';
export {RequireExactlyOne} from './source/require-exactly-one';
export {RequireAllOrNone} from './source/require-all-or-none';
export {RemoveIndexSignature} from './source/remove-index-signature';
export {PartialDeep, PartialDeepOptions} from './source/partial-deep';
export {PartialOnUndefinedDeep, PartialOnUndefinedDeepOptions} from './source/partial-on-undefined-deep';
export {ReadonlyDeep} from './source/readonly-deep';
export {LiteralUnion} from './source/literal-union';
export {Promisable} from './source/promisable';
export {Opaque, UnwrapOpaque} from './source/opaque';
export {InvariantOf} from './source/invariant-of';
export {SetOptional} from './source/set-optional';
export {SetRequired} from './source/set-required';
export {SetNonNullable} from './source/set-non-nullable';
export {ValueOf} from './source/value-of';
export {PromiseValue} from './source/promise-value';
export {AsyncReturnType} from './source/async-return-type';
export {ConditionalExcept} from './source/conditional-except';
export {ConditionalKeys} from './source/conditional-keys';
export {ConditionalPick} from './source/conditional-pick';
export {UnionToIntersection} from './source/union-to-intersection';
export {Stringified} from './source/stringified';
export {FixedLengthArray} from './source/fixed-length-array';
export {MultidimensionalArray} from './source/multidimensional-array';
export {MultidimensionalReadonlyArray} from './source/multidimensional-readonly-array';
export {IterableElement} from './source/iterable-element';
export {Entry} from './source/entry';
export {Entries} from './source/entries';
export {SetReturnType} from './source/set-return-type';
export {Asyncify} from './source/asyncify';
export {Simplify, SimplifyOptions} from './source/simplify';
export {Jsonify} from './source/jsonify';
export {Schema} from './source/schema';
export {LiteralToPrimitive} from './source/literal-to-primitive';
export {
PositiveInfinity,
NegativeInfinity,
Finite,
Integer,
Float,
NegativeFloat,
Negative,
NonNegative,
NegativeInteger,
NonNegativeInteger,
} from './source/numeric';
export {StringKeyOf} from './source/string-key-of';
export {Exact} from './source/exact';
export {ReadonlyTuple} from './source/readonly-tuple';
export {OptionalKeysOf} from './source/optional-keys-of';
export {HasOptionalKeys} from './source/has-optional-keys';
export {RequiredKeysOf} from './source/required-keys-of';
export {HasRequiredKeys} from './source/has-required-keys';
export {Spread} from './source/spread';
// Template literal types
export {CamelCase} from './source/camel-case';
export {CamelCasedProperties} from './source/camel-cased-properties';
export {CamelCasedPropertiesDeep} from './source/camel-cased-properties-deep';
export {KebabCase} from './source/kebab-case';
export {KebabCasedProperties} from './source/kebab-cased-properties';
export {KebabCasedPropertiesDeep} from './source/kebab-cased-properties-deep';
export {PascalCase} from './source/pascal-case';
export {PascalCasedProperties} from './source/pascal-cased-properties';
export {PascalCasedPropertiesDeep} from './source/pascal-cased-properties-deep';
export {SnakeCase} from './source/snake-case';
export {SnakeCasedProperties} from './source/snake-cased-properties';
export {SnakeCasedPropertiesDeep} from './source/snake-cased-properties-deep';
export {ScreamingSnakeCase} from './source/screaming-snake-case';
export {DelimiterCase} from './source/delimiter-case';
export {DelimiterCasedProperties} from './source/delimiter-cased-properties';
export {DelimiterCasedPropertiesDeep} from './source/delimiter-cased-properties-deep';
export {Join} from './source/join';
export {Split} from './source/split';
export {Trim} from './source/trim';
export {Replace} from './source/replace';
export {Includes} from './source/includes';
export {Get} from './source/get';
export {LastArrayElement} from './source/last-array-element';
// Miscellaneous
export {PackageJson} from './source/package-json';
export {TsConfigJson} from './source/tsconfig-json';

52
node_modules/type-fest/package.json generated vendored Normal file
View File

@@ -0,0 +1,52 @@
{
"name": "type-fest",
"version": "2.19.0",
"description": "A collection of essential TypeScript types",
"license": "(MIT OR CC0-1.0)",
"repository": "sindresorhus/type-fest",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=12.20"
},
"scripts": {
"test": "xo && tsd && tsc && node script/test/source-files-extension.js"
},
"files": [
"index.d.ts",
"source"
],
"keywords": [
"typescript",
"ts",
"types",
"utility",
"util",
"utilities",
"omit",
"merge",
"json"
],
"devDependencies": {
"@sindresorhus/tsconfig": "~0.7.0",
"expect-type": "^0.13.0",
"tsd": "^0.20.0",
"typescript": "^4.6.3",
"xo": "^0.43.0"
},
"types": "./index.d.ts",
"xo": {
"rules": {
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/indent": "off",
"node/no-unsupported-features/es-builtins": "off",
"import/extensions": "off",
"@typescript-eslint/no-redeclare": "off",
"@typescript-eslint/no-confusing-void-expression": "off"
}
}
}

905
node_modules/type-fest/readme.md generated vendored Normal file
View File

@@ -0,0 +1,905 @@
<div align="center">
<br>
<br>
<img src="media/logo.svg" alt="type-fest" height="300">
<br>
<br>
<b>A collection of essential TypeScript types</b>
<br>
<br>
<br>
<br>
<hr>
<div align="center">
<p>
<p>
<sup>
<a href="https://github.com/sponsors/sindresorhus">Sindre Sorhus' open source work is supported by the community</a>
</sup>
</p>
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://standardresume.co/tech">
<img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="180"/>
</a>
<br>
<br>
<br>
<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=type-fest&utm_source=github">
<div>
<img src="https://sindresorhus.com/assets/thanks/workos-logo-white-bg.svg" width="220" alt="WorkOS">
</div>
<b>Your app, enterprise-ready.</b>
<div>
<sub>Start selling to enterprise customers with just a few lines of code.</sub>
<br>
<sup>Add Single Sign-On (and more) in minutes instead of months.</sup>
</div>
</a>
<br>
<br>
<br>
<a href="https://www.useanvil.com/?utm_source=sindresorhus#gh-light-mode-only">
<div>
<img src="https://sindresorhus.com/assets/thanks/anvil-logo-light.svg" width="200" alt="Anvil">
</div>
<br>
<b>Paperwork that makes the data work.</b>
<div>
<sub>
Easy APIs for paperwork. PDF generation, e-signature and embeddable no-code webforms.
<br>
The easiest way to build paperwork automation into your product.
</sub>
</div>
</a>
<a href="https://www.useanvil.com/?utm_source=sindresorhus#gh-dark-mode-only">
<div>
<img src="https://sindresorhus.com/assets/thanks/anvil-logo-dark.svg" width="200" alt="Anvil">
</div>
<br>
<b>Paperwork that makes the data work.</b>
<div>
<sub>
Easy APIs for paperwork. PDF generation, e-signature and embeddable no-code webforms.
<br>
The easiest way to build paperwork automation into your product.
</sub>
</div>
</a>
</p>
</div>
<br>
<hr>
</div>
<br>
<br>
[![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://giphy.com/gifs/illustration-rainbow-unicorn-26AHG5KGFxSkUWw1i)
[![npm dependents](https://badgen.net/npm/dependents/type-fest)](https://www.npmjs.com/package/type-fest?activeTab=dependents)
[![npm downloads](https://badgen.net/npm/dt/type-fest)](https://www.npmjs.com/package/type-fest)
[![Docs](https://paka.dev/badges/v0/cute.svg)](https://paka.dev/npm/type-fest)
Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/main/CONTRIBUTING.md).
Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first.
**Help wanted with reviewing [proposals](https://github.com/sindresorhus/type-fest/issues) and [pull requests](https://github.com/sindresorhus/type-fest/pulls).**
## Install
```sh
npm install type-fest
```
*Requires TypeScript >=4.2*
## Usage
```ts
import type {Except} from 'type-fest';
type Foo = {
unicorn: string;
rainbow: boolean;
};
type FooWithoutRainbow = Except<Foo, 'rainbow'>;
//=> {unicorn: string}
```
## API
Click the type names for complete docs.
### Basic
- [`Primitive`](source/primitive.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
- [`Class`](source/basic.d.ts) - Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
- [`Constructor`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
- [`TypedArray`](source/typed-array.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
- [`ObservableLike`](source/observable-like.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
### Utilities
- [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys).
- [`Writable`](source/writable.d.ts) - Create a type that strips `readonly` from all or some of an object's keys. The inverse of `Readonly<T>`. Formerly named `Mutable`.
- [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type.
- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys.
- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more.
- [`RequireAllOrNone`](source/require-all-or-none.d.ts) - Create a type that requires all of the given keys or none of the given keys.
- [`RemoveIndexSignature`](source/remove-index-signature.d.ts) - Create a type that only has explicitly defined properties, absent of any index signatures.
- [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) if you only need one level deep.
- [`PartialOnUndefinedDeep`](source/partial-on-undefined-deep.d.ts) - Create a deep version of another type where all keys accepting `undefined` type are set to optional.
- [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) if you only need one level deep.
- [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729).
- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
- [`UnwrapOpaque`](source/opaque.d.ts) - Revert an [opaque type](https://codemix.com/opaque-types-in-javascript/) back to its original type.
- [`InvariantOf`](source/invariant-of.d.ts) - Create an [invariant type](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance), which is a type that does not accept supertypes and subtypes.
- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
- [`SetNonNullable`](source/set-non-nullable.d.ts) - Create a type that makes the given keys non-nullable.
- [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from.
- [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type.
- [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type.
- [`ConditionalExcept`](source/conditional-except.d.ts) - Like `Omit` except it removes properties from a shape where the values extend the given `Condition` type.
- [`UnionToIntersection`](source/union-to-intersection.d.ts) - Convert a union type to an intersection type.
- [`LiteralToPrimitive`](source/literal-to-primitive.d.ts) - Convert a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) to the [primitive type](source/primitive.d.ts) it belongs to.
- [`Stringified`](source/stringified.d.ts) - Create a type with the keys of the given type changed to `string` type.
- [`IterableElement`](source/iterable-element.d.ts) - Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
- [`Entry`](source/entry.d.ts) - Create a type that represents the type of an entry of a collection.
- [`Entries`](source/entries.d.ts) - Create a type that represents the type of the entries of a collection.
- [`SetReturnType`](source/set-return-type.d.ts) - Create a function type with a return type of your choice and the same parameters as the given function type.
- [`Simplify`](source/simplify.d.ts) - Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
- [`Get`](source/get.d.ts) - Get a deeply-nested property from an object using a key path, like [Lodash's `.get()`](https://lodash.com/docs/latest#get) function.
- [`StringKeyOf`](source/string-key-of.d.ts) - Get keys of the given type as strings.
- [`Schema`](source/schema.d.ts) - Create a deep version of another object type where property values are recursively replaced into a given value type.
- [`Exact`](source/exact.d.ts) - Create a type that does not allow extra properties.
- [`OptionalKeysOf`](source/optional-keys-of.d.ts) - Extract all optional keys from the given type.
- [`HasOptionalKeys`](source/has-optional-keys.d.ts) - Create a `true`/`false` type depending on whether the given type has any optional fields.
- [`RequiredKeysOf`](source/required-keys-of.d.ts) - Extract all required keys from the given type.
- [`HasRequiredKeys`](source/has-required-keys.d.ts) - Create a `true`/`false` type depending on whether the given type has any required fields.
- [`Spread`](source/spread.d.ts) - Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.
### JSON
- [`Jsonify`](source/jsonify.d.ts) - Transform a type to one that is assignable to the `JsonValue` type.
- [`JsonPrimitive`](source/basic.d.ts) - Matches a JSON primitive.
- [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
- [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
- [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value.
### Async
- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`.
- [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`.
- [`Asyncify`](source/asyncify.d.ts) - Create an async version of the given function type.
### String
- [`Trim`](source/trim.d.ts) - Remove leading and trailing spaces from a string.
- [`Split`](source/split.d.ts) - Represents an array of strings split using a given character or character set.
- [`Replace`](source/replace.d.ts) - Represents a string with some or all matches replaced by a replacement.
### Array
- [`Includes`](source/includes.d.ts) - Returns a boolean for whether the given array includes the given item.
- [`Join`](source/join.d.ts) - Join an array of strings and/or numbers using the given string as a delimiter.
- [`LastArrayElement`](source/last-array-element.d.ts) - Extracts the type of the last element of an array.
- [`FixedLengthArray`](source/fixed-length-array.d.ts) - Create a type that represents an array of the given type and length.
- [`MultidimensionalArray`](source/multidimensional-array.d.ts) - Create a type that represents a multidimensional array of the given type and dimensions.
- [`MultidimensionalReadonlyArray`](source/multidimensional-readonly-array.d.ts) - Create a type that represents a multidimensional readonly array of the given type and dimensions.
- [`ReadonlyTuple`](source/readonly-tuple.d.ts) - Create a type that represents a read-only tuple of the given type and length.
### Numeric
- [`PositiveInfinity`](source/numeric.d.ts) - Matches the hidden `Infinity` type.
- [`NegativeInfinity`](source/numeric.d.ts) - Matches the hidden `-Infinity` type.
- [`Finite`](source/numeric.d.ts) - A finite `number`.
- [`Integer`](source/numeric.d.ts) - A `number` that is an integer.
- [`Float`](source/numeric.d.ts) - A `number` that is not an integer.
- [`NegativeFloat`](source/numeric.d.ts) - A negative (`-∞ < x < 0`) `number` that is not an integer.
- [`Negative`](source/numeric.d.ts) - A negative `number`/`bigint` (`-∞ < x < 0`)
- [`NonNegative`](source/numeric.d.ts) - A non-negative `number`/`bigint` (`0 <= x < ∞`).
- [`NegativeInteger`](source/numeric.d.ts) - A negative (`-∞ < x < 0`) `number` that is an integer.
- [`NonNegativeInteger`](source/numeric.d.ts) - A non-negative (`0 <= x < ∞`) `number` that is an integer.
### Change case
- [`CamelCase`](source/camel-case.d.ts) - Convert a string literal to camel-case (`fooBar`).
- [`CamelCasedProperties`](source/camel-cased-properties.d.ts) - Convert object properties to camel-case (`fooBar`).
- [`CamelCasedPropertiesDeep`](source/camel-cased-properties-deep.d.ts) - Convert object properties to camel-case recursively (`fooBar`).
- [`KebabCase`](source/kebab-case.d.ts) - Convert a string literal to kebab-case (`foo-bar`).
- [`KebabCasedProperties`](source/kebab-cased-properties.d.ts) - Convert a object properties to kebab-case recursively (`foo-bar`).
- [`KebabCasedPropertiesDeep`](source/kebab-cased-properties-deep.d.ts) - Convert object properties to kebab-case (`foo-bar`).
- [`PascalCase`](source/pascal-case.d.ts) - Converts a string literal to pascal-case (`FooBar`)
- [`PascalCasedProperties`](source/pascal-cased-properties.d.ts) - Converts object properties to pascal-case (`FooBar`)
- [`PascalCasedPropertiesDeep`](source/pascal-cased-properties-deep.d.ts) - Converts object properties to pascal-case (`FooBar`)
- [`SnakeCase`](source/snake-case.d.ts) - Convert a string literal to snake-case (`foo_bar`).
- [`SnakeCasedProperties`](source/snake-cased-properties-deep.d.ts) - Convert object properties to snake-case (`foo_bar`).
- [`SnakeCasedPropertiesDeep`](source/snake-cased-properties-deep.d.ts) - Convert object properties to snake-case recursively (`foo_bar`).
- [`ScreamingSnakeCase`](source/screaming-snake-case.d.ts) - Convert a string literal to screaming-snake-case (`FOO_BAR`).
- [`DelimiterCase`](source/delimiter-case.d.ts) - Convert a string literal to a custom string delimiter casing.
- [`DelimiterCasedProperties`](source/delimiter-cased-properties.d.ts) - Convert object properties to a custom string delimiter casing.
- [`DelimiterCasedPropertiesDeep`](source/delimiter-cased-properties-deep.d.ts) - Convert object properties to a custom string delimiter casing recursively.
### Miscellaneous
- [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). It also includes support for [TypeScript Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) and [Yarn Workspaces](https://classic.yarnpkg.com/lang/en/docs/workspaces/).
- [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 4.4).
## Declined types
*If we decline a type addition, we will make sure to document the better solution here.*
- [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The pull request author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider.
- [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary<number>` vs `Record<string, number>`) from [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now.
- [`ExtractProperties` and `ExtractMethods`](https://github.com/sindresorhus/type-fest/pull/4) - The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies.
- [`Url2Json`](https://github.com/sindresorhus/type-fest/pull/262) - Inferring search parameters from a URL string is a cute idea, but not very useful in practice, since search parameters are usually dynamic and defined separately.
- [`Nullish`](https://github.com/sindresorhus/type-fest/pull/318) - The type only saves a couple of characters, not everyone knows what "nullish" means, and I'm also trying to [get away from `null`](https://github.com/sindresorhus/meta/discussions/7).
- [`TitleCase`](https://github.com/sindresorhus/type-fest/pull/303) - It's not solving a common need and is a better fit for a separate package.
- [`ExtendOr` and `ExtendAnd`](https://github.com/sindresorhus/type-fest/pull/247) - The benefits don't outweigh having to learn what they mean.
- [`PackageJsonExtras`](https://github.com/sindresorhus/type-fest/issues/371) - There are too many possible configurations that can be put into `package.json`. If you would like to extend `PackageJson` to support an additional configuration in your project, please see the *Extending existing types* section below.
## Alternative type names
*If you know one of our types by a different name, add it here for discovery.*
- `PartialBy` - See [`SetOptional`](https://github.com/sindresorhus/type-fest/blob/main/source/set-optional.d.ts)
- `RecordDeep`- See [`Schema`](https://github.com/sindresorhus/type-fest/blob/main/source/schema.d.ts)
## Tips
### Extending existing types
- [`PackageJson`](source/package-json.d.ts) - There are a lot of tools that place extra configurations inside the `package.json` file. You can extend `PackageJson` to support these additional configurations.
<details>
<summary>
Example
</summary>
[Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBDAnmApnA3gBQIYGMDW2A5igFIDOEAdnNuXAEJ0o4HFmVUC+cAZlBBBwA5ElQBaXinIxhAbgCwAKFCRYCZGnQAZYFRgooPfoJHSANntmKlysWlaESFanAC8jZo-YuaAMgwLKwBhal5gIgB+AC44XX1DADpQqnCiLhsgA)
```ts
import type {PackageJson as BasePackageJson} from 'type-fest';
import type {Linter} from 'eslint';
type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config};
```
</details>
### Related
- [typed-query-selector](https://github.com/g-plane/typed-query-selector) - Enhances `document.querySelector` and `document.querySelectorAll` with a template literal type that matches element types returned from an HTML element query selector.
- [`Linter.Config`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/eslint/index.d.ts) - Definitions for the [ESLint configuration schema](https://eslint.org/docs/user-guide/configuring/language-options).
### Built-in types
There are many advanced types most users don't know about.
- [`Partial<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) - Make all properties in `T` optional.
<details>
<summary>
Example
</summary>
[Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA)
```ts
interface NodeConfig {
appName: string;
port: number;
}
class NodeAppBuilder {
private configuration: NodeConfig = {
appName: 'NodeApp',
port: 3000
};
private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) {
this.configuration[key] = value;
}
config(config: Partial<NodeConfig>) {
type NodeConfigKey = keyof NodeConfig;
for (const key of Object.keys(config) as NodeConfigKey[]) {
const updateValue = config[key];
if (updateValue === undefined) {
continue;
}
this.updateConfig(key, updateValue);
}
return this;
}
}
// `Partial<NodeConfig>`` allows us to provide only a part of the
// NodeConfig interface.
new NodeAppBuilder().config({appName: 'ToDoApp'});
```
</details>
- [`Required<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype) - Make all properties in `T` required.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA)
```ts
interface ContactForm {
email?: string;
message?: string;
}
function submitContactForm(formData: Required<ContactForm>) {
// Send the form data to the server.
}
submitContactForm({
email: 'ex@mple.com',
message: 'Hi! Could you tell me more about…',
});
// TypeScript error: missing property 'message'
submitContactForm({
email: 'ex@mple.com',
});
```
</details>
- [`Readonly<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) - Make all properties in `T` readonly.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA)
```ts
enum LogLevel {
Off,
Debug,
Error,
Fatal
};
interface LoggerConfig {
name: string;
level: LogLevel;
}
class Logger {
config: Readonly<LoggerConfig>;
constructor({name, level}: LoggerConfig) {
this.config = {name, level};
Object.freeze(this.config);
}
}
const config: LoggerConfig = {
name: 'MyApp',
level: LogLevel.Debug
};
const logger = new Logger(config);
// TypeScript Error: cannot assign to read-only property.
logger.config.level = LogLevel.Error;
// We are able to edit config variable as we please.
config.level = LogLevel.Error;
```
</details>
- [`Pick<T, K>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys) - From `T`, pick a set of properties whose keys are in the union `K`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA)
```ts
interface Article {
title: string;
thumbnail: string;
content: string;
}
// Creates new type out of the `Article` interface composed
// from the Articles' two properties: `title` and `thumbnail`.
// `ArticlePreview = {title: string; thumbnail: string}`
type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;
// Render a list of articles using only title and description.
function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
const articles = document.createElement('div');
for (const preview of previews) {
// Append preview to the articles.
}
return articles;
}
const articles = renderArticlePreviews([
{
title: 'TypeScript tutorial!',
thumbnail: '/assets/ts.jpg'
}
]);
```
</details>
- [`Record<K, T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) - Construct a type with a set of properties `K` of type `T`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA)
```ts
// Positions of employees in our company.
type MemberPosition = 'intern' | 'developer' | 'tech-lead';
// Interface describing properties of a single employee.
interface Employee {
firstName: string;
lastName: string;
yearsOfExperience: number;
}
// Create an object that has all possible `MemberPosition` values set as keys.
// Those keys will store a collection of Employees of the same position.
const team: Record<MemberPosition, Employee[]> = {
intern: [],
developer: [],
'tech-lead': [],
};
// Our team has decided to help John with his dream of becoming Software Developer.
team.intern.push({
firstName: 'John',
lastName: 'Doe',
yearsOfExperience: 0
});
// `Record` forces you to initialize all of the property keys.
// TypeScript Error: "tech-lead" property is missing
const teamEmpty: Record<MemberPosition, null> = {
intern: null,
developer: null,
};
```
</details>
- [`Exclude<T, U>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion) - Exclude from `T` those types that are assignable to `U`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA)
```ts
interface ServerConfig {
port: null | string | number;
}
type RequestHandler = (request: Request, response: Response) => void;
// Exclude `null` type from `null | string | number`.
// In case the port is equal to `null`, we will use default value.
function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
if (typeof port === 'string') {
return parseInt(port, 10);
}
return port;
}
function startServer(handler: RequestHandler, config: ServerConfig): void {
const server = require('http').createServer(handler);
const port = config.port === null ? 3000 : getPortValue(config.port);
server.listen(port);
}
```
</details>
- [`Extract<T, U>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union) - Extract from `T` those types that are assignable to `U`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA)
```ts
declare function uniqueId(): number;
const ID = Symbol('ID');
interface Person {
[ID]: number;
name: string;
age: number;
}
// Allows changing the person data as long as the property key is of string type.
function changePersonData<
Obj extends Person,
Key extends Extract<keyof Person, string>,
Value extends Obj[Key]
> (obj: Obj, key: Key, value: Value): void {
obj[key] = value;
}
// Tiny Andrew was born.
const andrew = {
[ID]: uniqueId(),
name: 'Andrew',
age: 0,
};
// Cool, we're fine with that.
changePersonData(andrew, 'name', 'Pony');
// Goverment didn't like the fact that you wanted to change your identity.
changePersonData(andrew, ID, uniqueId());
```
</details>
- [`NonNullable<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype) - Exclude `null` and `undefined` from `T`.
<details>
<summary>
Example
</summary>
Works with <a href="https://www.typescriptlang.org/tsconfig#strictNullChecks"><code>strictNullChecks</code></a> set to <code>true</code>.
[Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA)
```ts
type PortNumber = string | number | null;
/** Part of a class definition that is used to build a server */
class ServerBuilder {
portNumber!: NonNullable<PortNumber>;
port(this: ServerBuilder, port: PortNumber): ServerBuilder {
if (port == null) {
this.portNumber = 8000;
} else {
this.portNumber = port;
}
return this;
}
}
const serverBuilder = new ServerBuilder();
serverBuilder
.port('8000') // portNumber = '8000'
.port(null) // portNumber = 8000
.port(3000); // portNumber = 3000
// TypeScript error
serverBuilder.portNumber = null;
```
</details>
- [`Parameters<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype) - Obtain the parameters of a function type in a tuple.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA)
```ts
function shuffle(input: any[]): void {
// Mutate array randomly changing its' elements indexes.
}
function callNTimes<Fn extends (...args: any[]) => any> (func: Fn, callCount: number) {
// Type that represents the type of the received function parameters.
type FunctionParameters = Parameters<Fn>;
return function (...args: FunctionParameters) {
for (let i = 0; i < callCount; i++) {
func(...args);
}
}
}
const shuffleTwice = callNTimes(shuffle, 2);
```
</details>
- [`ConstructorParameters<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#constructorparameterstype) - Obtain the parameters of a constructor function type in a tuple.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA)
```ts
class ArticleModel {
title: string;
content?: string;
constructor(title: string) {
this.title = title;
}
}
class InstanceCache<T extends (new (...args: any[]) => any)> {
private ClassConstructor: T;
private cache: Map<string, InstanceType<T>> = new Map();
constructor (ctr: T) {
this.ClassConstructor = ctr;
}
getInstance (...args: ConstructorParameters<T>): InstanceType<T> {
const hash = this.calculateArgumentsHash(...args);
const existingInstance = this.cache.get(hash);
if (existingInstance !== undefined) {
return existingInstance;
}
return new this.ClassConstructor(...args);
}
private calculateArgumentsHash(...args: any[]): string {
// Calculate hash.
return 'hash';
}
}
const articleCache = new InstanceCache(ArticleModel);
const amazonArticle = articleCache.getInstance('Amazon forests burining!');
```
</details>
- [`ReturnType<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype) - Obtain the return type of a function type.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
```ts
/** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
function mapIter<
Elem,
Func extends (elem: Elem) => any,
Ret extends ReturnType<Func>
>(iter: Iterable<Elem>, callback: Func): Ret[] {
const mapped: Ret[] = [];
for (const elem of iter) {
mapped.push(callback(elem));
}
return mapped;
}
const setObject: Set<string> = new Set();
const mapObject: Map<number, string> = new Map();
mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]
mapIter(mapObject, ([key, value]: [number, string]) => {
return key % 2 === 0 ? value : 'Odd';
}); // string[]
```
</details>
- [`InstanceType<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype) - Obtain the instance type of a constructor function type.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
```ts
class IdleService {
doNothing (): void {}
}
class News {
title: string;
content: string;
constructor(title: string, content: string) {
this.title = title;
this.content = content;
}
}
const instanceCounter: Map<Function, number> = new Map();
interface Constructor {
new(...args: any[]): any;
}
// Keep track how many instances of `Constr` constructor have been created.
function getInstance<
Constr extends Constructor,
Args extends ConstructorParameters<Constr>
>(constructor: Constr, ...args: Args): InstanceType<Constr> {
let count = instanceCounter.get(constructor) || 0;
const instance = new constructor(...args);
instanceCounter.set(constructor, count + 1);
console.log(`Created ${count + 1} instances of ${Constr.name} class`);
return instance;
}
const idleService = getInstance(IdleService);
// Will log: `Created 1 instances of IdleService class`
const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...');
// Will log: `Created 1 instances of News class`
```
</details>
- [`Omit<T, K>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) - Constructs a type by picking all properties from T and then removing K.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA)
```ts
interface Animal {
imageUrl: string;
species: string;
images: string[];
paragraphs: string[];
}
// Creates new type with all properties of the `Animal` interface
// except 'images' and 'paragraphs' properties. We can use this
// type to render small hover tooltip for a wiki entry list.
type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;
function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
const container = document.createElement('div');
// Internal implementation.
return container;
}
```
</details>
- [`Uppercase<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype) - Transforms every character in a string into uppercase.
<details>
<summary>
Example
</summary>
```ts
type T = Uppercase<'hello'>; // 'HELLO'
type T2 = Uppercase<'foo' | 'bar'>; // 'FOO' | 'BAR'
type T3<S extends string> = Uppercase<`aB${S}`>;
type T4 = T3<'xYz'>; // 'ABXYZ'
type T5 = Uppercase<string>; // string
type T6 = Uppercase<any>; // any
type T7 = Uppercase<never>; // never
type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string'
```
</details>
- [`Lowercase<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#lowercasestringtype) - Transforms every character in a string into lowercase.
<details>
<summary>
Example
</summary>
```ts
type T = Lowercase<'HELLO'>; // 'hello'
type T2 = Lowercase<'FOO' | 'BAR'>; // 'foo' | 'bar'
type T3<S extends string> = Lowercase<`aB${S}`>;
type T4 = T3<'xYz'>; // 'abxyz'
type T5 = Lowercase<string>; // string
type T6 = Lowercase<any>; // any
type T7 = Lowercase<never>; // never
type T8 = Lowercase<42>; // Error, type 'number' does not satisfy the constraint 'string'
```
</details>
- [`Capitalize<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#capitalizestringtype) - Transforms the first character in a string into uppercase.
<details>
<summary>
Example
</summary>
```ts
type T = Capitalize<'hello'>; // 'Hello'
type T2 = Capitalize<'foo' | 'bar'>; // 'Foo' | 'Bar'
type T3<S extends string> = Capitalize<`aB${S}`>;
type T4 = T3<'xYz'>; // 'ABxYz'
type T5 = Capitalize<string>; // string
type T6 = Capitalize<any>; // any
type T7 = Capitalize<never>; // never
type T8 = Capitalize<42>; // Error, type 'number' does not satisfy the constraint 'string'
```
</details>
- [`Uncapitalize<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uncapitalizestringtype) - Transforms the first character in a string into lowercase.
<details>
<summary>
Example
</summary>
```ts
type T = Uncapitalize<'Hello'>; // 'hello'
type T2 = Uncapitalize<'Foo' | 'Bar'>; // 'foo' | 'bar'
type T3<S extends string> = Uncapitalize<`AB${S}`>;
type T4 = T3<'xYz'>; // 'aBxYz'
type T5 = Uncapitalize<string>; // string
type T6 = Uncapitalize<any>; // any
type T7 = Uncapitalize<never>; // never
type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string'
```
</details>
You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/utility-types.html).
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Jarek Radosz](https://github.com/CvX)
- [Dimitri Benin](https://github.com/BendingBender)
- [Pelle Wessman](https://github.com/voxpelli)
## License
SPDX-License-Identifier: (MIT OR CC0-1.0)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-type-fest?utm_source=npm-type-fest&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

25
node_modules/type-fest/source/async-return-type.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import type {PromiseValue} from './promise-value';
type AsyncFunction = (...args: any[]) => Promise<unknown>;
/**
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<typeof asyncFunction>;
async function doSomething(value: Value) {}
asyncFunction().then(value => doSomething(value));
```
@category Async
*/
export type AsyncReturnType<Target extends AsyncFunction> = PromiseValue<ReturnType<Target>>;

33
node_modules/type-fest/source/asyncify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,33 @@
import type {PromiseValue} from './promise-value';
import type {SetReturnType} from './set-return-type';
/**
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<typeof getFooSync>;
//=> type AsyncifiedFooGetter = (someArg: SomeType) => Promise<Foo>;
// 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<Foo>`.
// 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 type Asyncify<Fn extends (...args: any[]) => any> = SetReturnType<Fn, Promise<PromiseValue<ReturnType<Fn>>>>;

45
node_modules/type-fest/source/basic.d.ts generated vendored Normal file
View File

@@ -0,0 +1,45 @@
/**
Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
@category Class
*/
export type Class<T, Arguments extends unknown[] = any[]> = Constructor<T, Arguments> & {prototype: T};
/**
Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
@category Class
*/
export type Constructor<T, Arguments extends unknown[] = any[]> = new(...arguments_: Arguments) => T;
/**
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 type JsonObject = {[Key in string]?: JsonValue};
/**
Matches a JSON array.
@category JSON
*/
export type JsonArray = JsonValue[];
/**
Matches any valid JSON primitive value.
@category JSON
*/
export 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 type JsonValue = JsonPrimitive | JsonObject | JsonArray;

73
node_modules/type-fest/source/camel-case.d.ts generated vendored Normal file
View File

@@ -0,0 +1,73 @@
import type {WordSeparators} from '../source/internal';
import type {Split} from './split';
/**
Step by step takes the first item in an array literal, formats it and adds it to a string literal, and then recursively appends the remainder.
Only to be used by `CamelCaseStringArray<>`.
@see CamelCaseStringArray
*/
type InnerCamelCaseStringArray<Parts extends readonly any[], PreviousPart> =
Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
? FirstPart extends undefined
? ''
: FirstPart extends ''
? InnerCamelCaseStringArray<RemainingParts, PreviousPart>
: `${PreviousPart extends '' ? FirstPart : Capitalize<FirstPart>}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`
: '';
/**
Starts fusing the output of `Split<>`, an array literal of strings, into a camel-cased string literal.
It's separate from `InnerCamelCaseStringArray<>` to keep a clean API outwards to the rest of the code.
@see Split
*/
type CamelCaseStringArray<Parts extends readonly string[]> =
Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
? Uncapitalize<`${FirstPart}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`>
: never;
/**
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.
@example
```
import type {CamelCase} from 'type-fest';
// Simple
const someVariable: CamelCase<'foo-bar'> = 'fooBar';
// Advanced
type CamelCasedProperties<T> = {
[K in keyof T as CamelCase<K>]: T[K]
};
interface RawOptions {
'dry-run': boolean;
'full_family_name': string;
foo: number;
BAR: string;
QUZ_QUX: number;
'OTHER-FIELD': boolean;
}
const dbResult: CamelCasedProperties<RawOptions> = {
dryRun: true,
fullFamilyName: 'bar.js',
foo: 123,
bar: 'foo',
quzQux: 6,
otherField: false
};
```
@category Change case
@category Template literal
*/
export type CamelCase<K> = K extends string ? CamelCaseStringArray<Split<K extends Uppercase<K> ? Lowercase<K> : K, WordSeparators>> : K;

View File

@@ -0,0 +1,54 @@
import type {CamelCase} from './camel-case';
/**
Convert object properties to camel case recursively.
This can be useful when, for example, converting some API types from a different style.
@see CamelCasedProperties
@see CamelCase
@example
```
import type {CamelCasedPropertiesDeep} from 'type-fest';
interface User {
UserId: number;
UserName: string;
}
interface UserWithFriends {
UserInfo: User;
UserFriends: User[];
}
const result: CamelCasedPropertiesDeep<UserWithFriends> = {
userInfo: {
userId: 1,
userName: 'Tom',
},
userFriends: [
{
userId: 2,
userName: 'Jerry',
},
{
userId: 3,
userName: 'Spike',
},
],
};
```
@category Change case
@category Template literal
@category Object
*/
export type CamelCasedPropertiesDeep<Value> = Value extends Function
? Value
: Value extends Array<infer U>
? Array<CamelCasedPropertiesDeep<U>>
: Value extends Set<infer U>
? Set<CamelCasedPropertiesDeep<U>> : {
[K in keyof Value as CamelCase<K>]: CamelCasedPropertiesDeep<Value[K]>;
};

View File

@@ -0,0 +1,36 @@
import type {CamelCase} from './camel-case';
/**
Convert object properties to camel case but not recursively.
This can be useful when, for example, converting some API types from a different style.
@see CamelCasedPropertiesDeep
@see CamelCase
@example
```
import type {CamelCasedProperties} from 'type-fest';
interface User {
UserId: number;
UserName: string;
}
const result: CamelCasedProperties<User> = {
userId: 1,
userName: 'Tom',
};
```
@category Change case
@category Template literal
@category Object
*/
export type CamelCasedProperties<Value> = Value extends Function
? Value
: Value extends Array<infer U>
? Value
: {
[K in keyof Value as CamelCase<K>]: Value[K];
};

45
node_modules/type-fest/source/conditional-except.d.ts generated vendored Normal file
View File

@@ -0,0 +1,45 @@
import type {Except} from './except';
import type {ConditionalKeys} from './conditional-keys';
/**
Exclude keys from a shape that matches the given `Condition`.
This is useful when you want to create a new type with a specific set of keys from a shape. For example, you might want to exclude all the primitive properties from a class and form a new shape containing everything but the primitive properties.
@example
```
import type {Primitive, ConditionalExcept} from 'type-fest';
class Awesome {
name: string;
successes: number;
failures: bigint;
run() {}
}
type ExceptPrimitivesFromAwesome = ConditionalExcept<Awesome, Primitive>;
//=> {run: () => void}
```
@example
```
import type {ConditionalExcept} from 'type-fest';
interface Example {
a: string;
b: string | number;
c: () => void;
d: {};
}
type NonStringKeysOnly = ConditionalExcept<Example, string>;
//=> {b: string | number; c: () => void; d: {}}
```
@category Object
*/
export type ConditionalExcept<Base, Condition> = Except<
Base,
ConditionalKeys<Base, Condition>
>;

47
node_modules/type-fest/source/conditional-keys.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
/**
Extract the keys from a type where the value type of the key extends the given `Condition`.
Internally this is used for the `ConditionalPick` and `ConditionalExcept` types.
@example
```
import type {ConditionalKeys} from 'type-fest';
interface Example {
a: string;
b: string | number;
c?: string;
d: {};
}
type StringKeysOnly = ConditionalKeys<Example, string>;
//=> 'a'
```
To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below.
@example
```
import type {ConditionalKeys} from 'type-fest';
type StringKeysAndUndefined = ConditionalKeys<Example, string | undefined>;
//=> 'a' | 'c'
```
@category Object
*/
export type ConditionalKeys<Base, Condition> = NonNullable<
// Wrap in `NonNullable` to strip away the `undefined` type from the produced union.
{
// Map through all the keys of the given base type.
[Key in keyof Base]:
// Pick only keys with types extending the given `Condition` type.
Base[Key] extends Condition
// Retain this key since the condition passes.
? Key
// Discard this key since the condition fails.
: never;
// Convert the produced object into a union type of the keys which passed the conditional test.
}[keyof Base]
>;

44
node_modules/type-fest/source/conditional-pick.d.ts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import type {ConditionalKeys} from './conditional-keys';
/**
Pick keys from the shape that matches the given `Condition`.
This is useful when you want to create a new type from a specific subset of an existing type. For example, you might want to pick all the primitive properties from a class and form a new automatically derived type.
@example
```
import type {Primitive, ConditionalPick} from 'type-fest';
class Awesome {
name: string;
successes: number;
failures: bigint;
run() {}
}
type PickPrimitivesFromAwesome = ConditionalPick<Awesome, Primitive>;
//=> {name: string; successes: number; failures: bigint}
```
@example
```
import type {ConditionalPick} from 'type-fest';
interface Example {
a: string;
b: string | number;
c: () => void;
d: {};
}
type StringKeysOnly = ConditionalPick<Example, string>;
//=> {a: string}
```
@category Object
*/
export type ConditionalPick<Base, Condition> = Pick<
Base,
ConditionalKeys<Base, Condition>
>;

93
node_modules/type-fest/source/delimiter-case.d.ts generated vendored Normal file
View File

@@ -0,0 +1,93 @@
import type {UpperCaseCharacters, WordSeparators} from '../source/internal';
/**
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
*/
export type SplitIncludingDelimiters<Source extends string, Delimiter extends string> =
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<FirstPart, Delimiter>, UsedDelimiter, ...SplitIncludingDelimiters<SecondPart, Delimiter>]
: never
: never
: never
) :
[Source];
/**
Format a specific part of the splitted string literal that `StringArrayToDelimiterCase<>` fuses together, ensuring desired casing.
@see StringArrayToDelimiterCase
*/
type StringPartToDelimiterCase<StringPart extends string, Start extends boolean, UsedWordSeparators extends string, UsedUpperCaseCharacters extends string, Delimiter extends string> =
StringPart extends UsedWordSeparators ? Delimiter :
Start extends true ? Lowercase<StringPart> :
StringPart extends UsedUpperCaseCharacters ? `${Delimiter}${Lowercase<StringPart>}` :
StringPart;
/**
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
*/
type StringArrayToDelimiterCase<Parts extends readonly any[], Start extends boolean, UsedWordSeparators extends string, UsedUpperCaseCharacters extends string, Delimiter extends string> =
Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
? `${StringPartToDelimiterCase<FirstPart, Start, UsedWordSeparators, UsedUpperCaseCharacters, Delimiter>}${StringArrayToDelimiterCase<RemainingParts, false, UsedWordSeparators, UsedUpperCaseCharacters, Delimiter>}`
: Parts extends [string]
? string
: '';
/**
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<T> = {
[K in keyof T as DelimiterCase<K, '#'>]: T[K]
};
interface SomeOptions {
dryRun: boolean;
includeFile: string;
foo: number;
}
const rawCliOptions: OddlyCasedProperties<SomeOptions> = {
'dry#run': true,
'include#file': 'bar.js',
foo: 123
};
```
@category Change case
@category Template literal
*/
export type DelimiterCase<Value, Delimiter extends string> = Value extends string
? StringArrayToDelimiterCase<
SplitIncludingDelimiters<Value, WordSeparators | UpperCaseCharacters>,
true,
WordSeparators,
UpperCaseCharacters,
Delimiter
>
: Value;

View File

@@ -0,0 +1,60 @@
import type {DelimiterCase} from './delimiter-case';
/**
Convert object properties to delimiter case recursively.
This can be useful when, for example, converting some API types from a different style.
@see DelimiterCase
@see DelimiterCasedProperties
@example
```
import type {DelimiterCasedPropertiesDeep} from 'type-fest';
interface User {
userId: number;
userName: string;
}
interface UserWithFriends {
userInfo: User;
userFriends: User[];
}
const result: DelimiterCasedPropertiesDeep<UserWithFriends, '-'> = {
'user-info': {
'user-id': 1,
'user-name': 'Tom',
},
'user-friends': [
{
'user-id': 2,
'user-name': 'Jerry',
},
{
'user-id': 3,
'user-name': 'Spike',
},
],
};
```
@category Change case
@category Template literal
@category Object
*/
export type DelimiterCasedPropertiesDeep<
Value,
Delimiter extends string,
> = Value extends Function | Date | RegExp
? Value
: Value extends Array<infer U>
? Array<DelimiterCasedPropertiesDeep<U, Delimiter>>
: Value extends Set<infer U>
? Set<DelimiterCasedPropertiesDeep<U, Delimiter>> : {
[K in keyof Value as DelimiterCase<
K,
Delimiter
>]: DelimiterCasedPropertiesDeep<Value[K], Delimiter>;
};

View File

@@ -0,0 +1,37 @@
import type {DelimiterCase} from './delimiter-case';
/**
Convert object properties to delimiter case but not recursively.
This can be useful when, for example, converting some API types from a different style.
@see DelimiterCase
@see DelimiterCasedPropertiesDeep
@example
```
import type {DelimiterCasedProperties} from 'type-fest';
interface User {
userId: number;
userName: string;
}
const result: DelimiterCasedProperties<User, '-'> = {
'user-id': 1,
'user-name': 'Tom',
};
```
@category Change case
@category Template literal
@category Object
*/
export type DelimiterCasedProperties<
Value,
Delimiter extends string,
> = Value extends Function
? Value
: Value extends Array<infer U>
? Value
: {[K in keyof Value as DelimiterCase<K, Delimiter>]: Value[K]};

62
node_modules/type-fest/source/entries.d.ts generated vendored Normal file
View File

@@ -0,0 +1,62 @@
import type {ArrayEntry, MapEntry, ObjectEntry, SetEntry} from './entry';
type ArrayEntries<BaseType extends readonly unknown[]> = Array<ArrayEntry<BaseType>>;
type MapEntries<BaseType> = Array<MapEntry<BaseType>>;
type ObjectEntries<BaseType> = Array<ObjectEntry<BaseType>>;
type SetEntries<BaseType extends Set<unknown>> = Array<SetEntry<BaseType>>;
/**
Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entries` type will return the type of that collection's entries.
For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable.
@see `Entry` if you want to just access the type of a single entry.
@example
```
import type {Entries} from 'type-fest';
interface Example {
someKey: number;
}
const manipulatesEntries = (examples: Entries<Example>) => examples.map(example => [
// Does some arbitrary processing on the key (with type information available)
example[0].toUpperCase(),
// Does some arbitrary processing on the value (with type information available)
example[1].toFixed()
]);
const example: Example = {someKey: 1};
const entries = Object.entries(example) as Entries<Example>;
const output = manipulatesEntries(entries);
// Objects
const objectExample = {a: 1};
const objectEntries: Entries<typeof objectExample> = [['a', 1]];
// Arrays
const arrayExample = ['a', 1];
const arrayEntries: Entries<typeof arrayExample> = [[0, 'a'], [1, 1]];
// Maps
const mapExample = new Map([['a', 1]]);
const mapEntries: Entries<typeof map> = [['a', 1]];
// Sets
const setExample = new Set(['a', 1]);
const setEntries: Entries<typeof setExample> = [['a', 'a'], [1, 1]];
```
@category Object
@category Map
@category Set
@category Array
*/
export type Entries<BaseType> =
BaseType extends Map<unknown, unknown> ? MapEntries<BaseType>
: BaseType extends Set<unknown> ? SetEntries<BaseType>
: BaseType extends readonly unknown[] ? ArrayEntries<BaseType>
: BaseType extends object ? ObjectEntries<BaseType>
: never;

65
node_modules/type-fest/source/entry.d.ts generated vendored Normal file
View File

@@ -0,0 +1,65 @@
type MapKey<BaseType> = BaseType extends Map<infer KeyType, unknown> ? KeyType : never;
type MapValue<BaseType> = BaseType extends Map<unknown, infer ValueType> ? ValueType : never;
export type ArrayEntry<BaseType extends readonly unknown[]> = [number, BaseType[number]];
export type MapEntry<BaseType> = [MapKey<BaseType>, MapValue<BaseType>];
export type ObjectEntry<BaseType> = [keyof BaseType, BaseType[keyof BaseType]];
export type SetEntry<BaseType> = BaseType extends Set<infer ItemType> ? [ItemType, ItemType] : never;
/**
Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entry` type will return the type of that collection's entry.
For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable.
@see `Entries` if you want to just access the type of the array of entries (which is the return of the `.entries()` method).
@example
```
import type {Entry} from 'type-fest';
interface Example {
someKey: number;
}
const manipulatesEntry = (example: Entry<Example>) => [
// Does some arbitrary processing on the key (with type information available)
example[0].toUpperCase(),
// Does some arbitrary processing on the value (with type information available)
example[1].toFixed(),
];
const example: Example = {someKey: 1};
const entry = Object.entries(example)[0] as Entry<Example>;
const output = manipulatesEntry(entry);
// Objects
const objectExample = {a: 1};
const objectEntry: Entry<typeof objectExample> = ['a', 1];
// Arrays
const arrayExample = ['a', 1];
const arrayEntryString: Entry<typeof arrayExample> = [0, 'a'];
const arrayEntryNumber: Entry<typeof arrayExample> = [1, 1];
// Maps
const mapExample = new Map([['a', 1]]);
const mapEntry: Entry<typeof mapExample> = ['a', 1];
// Sets
const setExample = new Set(['a', 1]);
const setEntryString: Entry<typeof setExample> = ['a', 'a'];
const setEntryNumber: Entry<typeof setExample> = [1, 1];
```
@category Object
@category Map
@category Array
@category Set
*/
export type Entry<BaseType> =
BaseType extends Map<unknown, unknown> ? MapEntry<BaseType>
: BaseType extends Set<unknown> ? SetEntry<BaseType>
: BaseType extends readonly unknown[] ? ArrayEntry<BaseType>
: BaseType extends object ? ObjectEntry<BaseType>
: never;

73
node_modules/type-fest/source/exact.d.ts generated vendored Normal file
View File

@@ -0,0 +1,73 @@
import type {KeysOfUnion} from './internal';
/**
Extract the element of an array that also works for array union.
Returns `never` if T is not an array.
It creates a type-safe way to access the element type of `unknown` type.
*/
type ArrayElement<T> = T extends readonly unknown[] ? T[0] : never;
/**
Extract the object field type if T is an object and K is a key of T, return `never` otherwise.
It creates a type-safe way to access the member type of `unknown` type.
*/
type ObjectValue<T, K> = K extends keyof T ? T[K] : never;
/**
Create a type from `ParameterType` and `InputType` and change keys exclusive to `InputType` to `never`.
- Generate a list of keys that exists in `InputType` but not in `ParameterType`.
- Mark these excess keys as `never`.
*/
type ExactObject<ParameterType, InputType> = {[Key in keyof ParameterType]: Exact<ParameterType[Key], ObjectValue<InputType, Key>>}
& Record<Exclude<keyof InputType, KeysOfUnion<ParameterType>>, never>;
/**
Create a type that does not allow extra properties, meaning it only allows properties that are explicitly declared.
This is useful for function type-guarding to reject arguments with excess properties. Due to the nature of TypeScript, it does not complain if excess properties are provided unless the provided value is an object literal.
*Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/12936) if you want to have this type as a built-in in TypeScript.*
@example
```
type OnlyAcceptName = {name: string};
function onlyAcceptName(args: OnlyAcceptName) {}
// TypeScript complains about excess properties when an object literal is provided.
onlyAcceptName({name: 'name', id: 1});
//=> `id` is excess
// TypeScript does not complain about excess properties when the provided value is a variable (not an object literal).
const invalidInput = {name: 'name', id: 1};
onlyAcceptName(invalidInput); // No errors
```
Having `Exact` allows TypeScript to reject excess properties.
@example
```
import {Exact} from 'type-fest';
type OnlyAcceptName = {name: string};
function onlyAcceptNameImproved<T extends Exact<OnlyAcceptName, T>>(args: T) {}
const invalidInput = {name: 'name', id: 1};
onlyAcceptNameImproved(invalidInput); // Compilation error
```
[Read more](https://stackoverflow.com/questions/49580725/is-it-possible-to-restrict-typescript-object-to-contain-only-properties-defined)
@category Utilities
*/
export type Exact<ParameterType, InputType> =
// Convert union of array to array of union: A[] & B[] => (A & B)[]
ParameterType extends unknown[] ? Array<Exact<ArrayElement<ParameterType>, ArrayElement<InputType>>>
// In TypeScript, Array is a subtype of ReadonlyArray, so always test Array before ReadonlyArray.
: ParameterType extends readonly unknown[] ? ReadonlyArray<Exact<ArrayElement<ParameterType>, ArrayElement<InputType>>>
: ParameterType extends object ? ExactObject<ParameterType, InputType>
: ParameterType;

57
node_modules/type-fest/source/except.d.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import type {IsEqual} from './internal';
/**
Filter out keys from an object.
Returns `never` if `Exclude` is strictly equal to `Key`.
Returns `never` if `Key` extends `Exclude`.
Returns `Key` otherwise.
@example
```
type Filtered = Filter<'foo', 'foo'>;
//=> never
```
@example
```
type Filtered = Filter<'bar', string>;
//=> never
```
@example
```
type Filtered = Filter<'bar', 'foo'>;
//=> 'bar'
```
@see {Except}
*/
type Filter<KeyType, ExcludeType> = IsEqual<KeyType, ExcludeType> extends true ? never : (KeyType extends ExcludeType ? never : KeyType);
/**
Create a type from an object type without certain keys.
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;
c: boolean;
};
type FooWithoutA = Except<Foo, 'a' | 'c'>;
//=> {b: string};
```
@category Object
*/
export type Except<ObjectType, KeysType extends keyof ObjectType> = {
[KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType];
};

43
node_modules/type-fest/source/fixed-length-array.d.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
/**
Methods to exclude.
*/
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift';
/**
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 similiar 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<string, 3>;
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 type FixedLengthArray<Element, Length extends number, ArrayPrototype = [Element, ...Element[]]> = Pick<
ArrayPrototype,
Exclude<keyof ArrayPrototype, ArrayLengthMutationKeys>
> & {
[index: number]: Element;
[Symbol.iterator]: () => IterableIterator<Element>;
readonly length: Length;
};

184
node_modules/type-fest/source/get.d.ts generated vendored Normal file
View File

@@ -0,0 +1,184 @@
import type {StringDigit} from '../source/internal';
import type {Split} from './split';
import type {StringKeyOf} from './string-key-of';
type GetOptions = {
strict?: boolean;
};
/**
Like the `Get` type but receives an array of strings as a path parameter.
*/
type GetWithPath<BaseType, Keys extends readonly string[], Options extends GetOptions = {}> =
Keys extends []
? BaseType
: Keys extends readonly [infer Head, ...infer Tail]
? GetWithPath<
PropertyOf<BaseType, Extract<Head, string>, Options>,
Extract<Tail, string[]>,
Options
>
: never;
/**
Adds `undefined` to `Type` if `strict` is enabled.
*/
type Strictify<Type, Options extends GetOptions> =
Options['strict'] extends true ? Type | undefined : Type;
/**
If `Options['strict']` is `true`, includes `undefined` in the returned type when accessing properties on `Record<string, any>`.
Known limitations:
- Does not include `undefined` in the type on object types with an index signature (for example, `{a: string; [key: string]: string}`).
*/
type StrictPropertyOf<BaseType, Key extends keyof BaseType, Options extends GetOptions> =
Record<string, any> extends BaseType
? string extends keyof BaseType
? Strictify<BaseType[Key], Options> // Record<string, any>
: BaseType[Key] // Record<'a' | 'b', any> (Records with a string union as keys have required properties)
: BaseType[Key];
/**
Splits a dot-prop style path into a tuple comprised of the properties in the path. Handles square-bracket notation.
@example
```
ToPath<'foo.bar.baz'>
//=> ['foo', 'bar', 'baz']
ToPath<'foo[0].bar.baz'>
//=> ['foo', '0', 'bar', 'baz']
```
*/
type ToPath<S extends string> = Split<FixPathSquareBrackets<S>, '.'>;
/**
Replaces square-bracketed dot notation with dots, for example, `foo[0].bar` -> `foo.0.bar`.
*/
type FixPathSquareBrackets<Path extends string> =
Path extends `[${infer Head}]${infer Tail}`
? Tail extends `[${string}`
? `${Head}.${FixPathSquareBrackets<Tail>}`
: `${Head}${FixPathSquareBrackets<Tail>}`
: Path extends `${infer Head}[${infer Middle}]${infer Tail}`
? `${Head}.${FixPathSquareBrackets<`[${Middle}]${Tail}`>}`
: Path;
/**
Returns true if `LongString` is made up out of `Substring` repeated 0 or more times.
@example
```
ConsistsOnlyOf<'aaa', 'a'> //=> true
ConsistsOnlyOf<'ababab', 'ab'> //=> true
ConsistsOnlyOf<'aBa', 'a'> //=> false
ConsistsOnlyOf<'', 'a'> //=> true
```
*/
type ConsistsOnlyOf<LongString extends string, Substring extends string> =
LongString extends ''
? true
: LongString extends `${Substring}${infer Tail}`
? ConsistsOnlyOf<Tail, Substring>
: false;
/**
Convert a type which may have number keys to one with string keys, making it possible to index using strings retrieved from template types.
@example
```
type WithNumbers = {foo: string; 0: boolean};
type WithStrings = WithStringKeys<WithNumbers>;
type WithNumbersKeys = keyof WithNumbers;
//=> 'foo' | 0
type WithStringsKeys = keyof WithStrings;
//=> 'foo' | '0'
```
*/
type WithStringKeys<BaseType> = {
[Key in StringKeyOf<BaseType>]: UncheckedIndex<BaseType, Key>
};
/**
Perform a `T[U]` operation if `T` supports indexing.
*/
type UncheckedIndex<T, U extends string | number> = [T] extends [Record<string | number, any>] ? T[U] : never;
/**
Get a property of an object or array. Works when indexing arrays using number-literal-strings, for example, `PropertyOf<number[], '0'> = number`, and when indexing objects with number keys.
Note:
- Returns `unknown` if `Key` is not a property of `BaseType`, since TypeScript uses structural typing, and it cannot be guaranteed that extra properties unknown to the type system will exist at runtime.
- Returns `undefined` from nullish values, to match the behaviour of most deep-key libraries like `lodash`, `dot-prop`, etc.
*/
type PropertyOf<BaseType, Key extends string, Options extends GetOptions = {}> =
BaseType extends null | undefined
? undefined
: Key extends keyof BaseType
? StrictPropertyOf<BaseType, Key, Options>
: BaseType extends [] | [unknown, ...unknown[]]
? unknown // It's a tuple, but `Key` did not extend `keyof BaseType`. So the index is out of bounds.
: BaseType extends {
[n: number]: infer Item;
length: number; // Note: This is needed to avoid being too lax with records types using number keys like `{0: string; 1: boolean}`.
}
? (
ConsistsOnlyOf<Key, StringDigit> extends true
? Strictify<Item, Options>
: unknown
)
: Key extends keyof WithStringKeys<BaseType>
? StrictPropertyOf<WithStringKeys<BaseType>, Key, Options>
: unknown;
// This works by first splitting the path based on `.` and `[...]` characters into a tuple of string keys. Then it recursively uses the head key to get the next property of the current object, until there are no keys left. Number keys extract the item type from arrays, or are converted to strings to extract types from tuples and dictionaries with number keys.
/**
Get a deeply-nested property from an object using a key path, like Lodash's `.get()` function.
Use-case: Retrieve a property from deep inside an API response or some other complex object.
@example
```
import type {Get} from 'type-fest';
import * as lodash from 'lodash';
const get = <BaseType, Path extends string | readonly string[]>(object: BaseType, path: Path): Get<BaseType, Path> =>
lodash.get(object, path);
interface ApiResponse {
hits: {
hits: Array<{
_id: string
_source: {
name: Array<{
given: string[]
family: string
}>
birthDate: string
}
}>
}
}
const getName = (apiResponse: ApiResponse) =>
get(apiResponse, 'hits.hits[0]._source.name');
//=> Array<{given: string[]; family: string}>
// Path also supports a readonly array of strings
const getNameWithPathArray = (apiResponse: ApiResponse) =>
get(apiResponse, ['hits','hits', '0', '_source', 'name'] as const);
//=> Array<{given: string[]; family: string}>
// Strict mode:
Get<string[], '3', {strict: true}> //=> string | undefined
Get<Record<string, string>, 'foo', {strict: true}> // => string | undefined
```
@category Object
@category Array
@category Template literal
*/
export type Get<BaseType, Path extends string | readonly string[], Options extends GetOptions = {}> =
GetWithPath<BaseType, Path extends string ? ToPath<Path> : Path, Options>;

21
node_modules/type-fest/source/has-optional-keys.d.ts generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import {OptionalKeysOf} from './optional-keys-of';
/**
Creates a type that represents `true` or `false` depending on whether the given type has any optional fields.
This is useful when you want to create an API whose behavior depends on the presence or absence of optional fields.
@example
```
import type {HasOptionalKeys, OptionalKeysOf} from 'type-fest';
type UpdateService<Entity extends object> = {
removeField: HasOptionalKeys<Entity> extends true
? (field: OptionalKeysOf<Entity>) => Promise<void>
: never
}
```
@category Utilities
*/
export type HasOptionalKeys<BaseType extends object> = OptionalKeysOf<BaseType> extends never ? false : true;

59
node_modules/type-fest/source/has-required-keys.d.ts generated vendored Normal file
View File

@@ -0,0 +1,59 @@
import {RequiredKeysOf} from './required-keys-of';
/**
Creates a type that represents `true` or `false` depending on whether the given type has any required fields.
This is useful when you want to create an API whose behavior depends on the presence or absence of required fields.
@example
```
import type {HasRequiredKeys} from 'type-fest';
type GeneratorOptions<Template extends object> = {
prop1: number;
prop2: string;
} & (HasRequiredKeys<Template> extends true
? {template: Template}
: {template?: Template});
interface Template1 {
optionalSubParam?: string;
}
interface Template2 {
requiredSubParam: string;
}
type Options1 = GeneratorOptions<Template1>;
type Options2 = GeneratorOptions<Template2>;
const optA: Options1 = {
prop1: 0,
prop2: 'hi'
};
const optB: Options1 = {
prop1: 0,
prop2: 'hi',
template: {}
};
const optC: Options1 = {
prop1: 0,
prop2: 'hi',
template: {
optionalSubParam: 'optional value'
}
};
const optD: Options2 = {
prop1: 0,
prop2: 'hi',
template: {
requiredSubParam: 'required value'
}
};
```
@category Utilities
*/
export type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;

22
node_modules/type-fest/source/includes.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import type {IsEqual} from './internal';
/**
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<array extends any[]> = Includes<array, 'red'>;
```
@category Array
*/
export type Includes<Value extends readonly any[], Item> =
Value extends readonly [Value[0], ...infer rest]
? IsEqual<Value[0], Item> extends true
? true
: Includes<rest, Item>
: false;

59
node_modules/type-fest/source/internal.d.ts generated vendored Normal file
View File

@@ -0,0 +1,59 @@
import type {Primitive} from './primitive';
/**
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
*/
export type IsEqual<T, U> =
(<G>() => G extends T ? 1 : 2) extends
(<G>() => G extends U ? 1 : 2)
? true
: false;
/**
Infer the length of the given array `<T>`.
@link https://itnext.io/implementing-arithmetic-within-typescripts-type-system-a1ef140a6f6f
*/
type TupleLength<T extends readonly unknown[]> = T extends {readonly length: infer L} ? L : never;
/**
Create a tuple type of the given length `<L>`.
@link https://itnext.io/implementing-arithmetic-within-typescripts-type-system-a1ef140a6f6f
*/
type BuildTuple<L extends number, T extends readonly unknown[] = []> = T extends {readonly length: L}
? T
: BuildTuple<L, [...T, unknown]>;
/**
Create a tuple of length `A` and a tuple composed of two other tuples,
the inferred tuple `U` and a tuple of length `B`, then extracts the length of tuple `U`.
@link https://itnext.io/implementing-arithmetic-within-typescripts-type-system-a1ef140a6f6f
*/
export type Subtract<A extends number, B extends number> = BuildTuple<A> extends [...(infer U), ...BuildTuple<B>]
? TupleLength<U>
: never;
/**
Matches any primitive, `Date`, or `RegExp` value.
*/
export type BuiltIns = Primitive | Date | RegExp;
/**
Gets keys from a type. Similar to `keyof` but this one also works for union types.
The reason a simple `keyof Union` does not work is because `keyof` always returns the accessible keys of a type. In the case of a union, that will only be the common keys.
@link https://stackoverflow.com/a/49402091
*/
export type KeysOfUnion<T> = T extends T ? keyof T : never;
export type UpperCaseCharacters = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z';
export type WordSeparators = '-' | '_' | ' ';
export type StringDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';

76
node_modules/type-fest/source/invariant-of.d.ts generated vendored Normal file
View File

@@ -0,0 +1,76 @@
import type {Opaque} from './opaque';
/**
Create an [invariant type](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance), which is a type that does not accept supertypes and subtypes.
Use-case:
- Prevent runtime errors that may occur due to assigning subtypes to supertypes.
- Improve type signature of object methods like [`Object.keys()` or `Object.entries()`](https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208) by sealing the object type.
@example
```
import type {InvariantOf} from 'type-fest';
class Animal {
constructor(public name: string){}
}
class Cat extends Animal {
meow() {}
}
let animalArray: Animal[] = [animal];
let catArray: Cat[] = [cat];
animalArray = catArray; // Okay if covariant
animalArray.push(new Animal('another animal')); // Pushed an animal into catArray
catArray.forEach(c => c.meow()); // Allowed but, error at runtime
let invariantAnimalArray: InvariantOf<Animal>[] = [animal] as InvariantOf<Animal>[];
let invariantCatArray: InvariantOf<Cat>[] = [cat] as InvariantOf<Cat>[];
invariantAnimalArray = invariantCatArray; // Error: Type 'InvariantOf<Cat>[]' is not assignable to type 'InvariantOf<Animal>[]'.
```
@example
```
import type {InvariantOf} from 'type-fest';
// In covariance (default)
interface FooBar {
foo: number;
bar: string
}
interface FooBarBaz extends FooBar {
baz: boolean
}
declare const fooBar: FooBar
declare const fooBarBaz: FooBarBaz
function keyOfFooBar(fooBar: FooBar) {
return Object.keys(fooBar) as (keyof FooBar)[]
}
keyOfFooBar(fooBar) //=> (keyof FooBar)[]
keyOfFooBar(fooBarBaz) //=> (keyof FooBar)[] but, (keyof FooBarBaz)[] at runtime
// In invariance
export function invariantOf<Type>(value: Type): InvariantOf<Type> {
return value as InvariantOf<Type>;
}
function keyOfInvariantFooBar(fooBar: InvariantOf<FooBar>) {
return Object.keys(fooBar) as (keyof FooBar)[]
}
keyOfInvariantFooBar(invariantOf(fooBar)); // (keyof FooBar)[]
keyOfInvariantFooBar(invariantOf(fooBarBaz)); // Error: Argument of type 'InvariantOf<FooBarBaz>' is not assignable to parameter of type 'InvariantOf<FooBar>'.
```
@category Type
*/
export type InvariantOf<Type> = Opaque<Type, (argument: Type) => Type>;

54
node_modules/type-fest/source/iterable-element.d.ts generated vendored Normal file
View File

@@ -0,0 +1,54 @@
/**
Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
This can be useful, for example, if you want to get the type that is yielded in a generator function. Often the return type of those functions are not specified.
This type works with both `Iterable`s and `AsyncIterable`s, so it can be use with synchronous and asynchronous generators.
Here is an example of `IterableElement` in action with a generator function:
@example
```
import type {IterableElement} from 'type-fest';
function * iAmGenerator() {
yield 1;
yield 2;
}
type MeNumber = IterableElement<ReturnType<typeof iAmGenerator>>
```
And here is an example with an async generator:
@example
```
import type {IterableElement} from 'type-fest';
async function * iAmGeneratorAsync() {
yield 'hi';
yield true;
}
type MeStringOrBoolean = IterableElement<ReturnType<typeof iAmGeneratorAsync>>
```
Many types in JavaScript/TypeScript are iterables. This type works on all types that implement those interfaces. For example, `Array`, `Set`, `Map`, `stream.Readable`, etc.
An example with an array of strings:
@example
```
import type {IterableElement} from 'type-fest';
type MeString = IterableElement<string[]>
```
@category Iterable
*/
export type IterableElement<TargetIterable> =
TargetIterable extends Iterable<infer ElementType> ?
ElementType :
TargetIterable extends AsyncIterable<infer ElementType> ?
ElementType :
never;

30
node_modules/type-fest/source/join.d.ts generated vendored Normal file
View File

@@ -0,0 +1,30 @@
/**
Join an array of strings and/or numbers using the given string as a delimiter.
Use-case: Defining key paths in a nested object. For example, for dot-notation fields in MongoDB queries.
@example
```
import type {Join} from 'type-fest';
// Mixed (strings & numbers) items; result is: 'foo.0.baz'
const path: Join<['foo', 0, 'baz'], '.'> = ['foo', 0, 'baz'].join('.');
// Only string items; result is: 'foo.bar.baz'
const path: Join<['foo', 'bar', 'baz'], '.'> = ['foo', 'bar', 'baz'].join('.');
// Only number items; result is: '1.2.3'
const path: Join<[1, 2, 3], '.'> = [1, 2, 3].join('.');
```
@category Array
@category Template literal
*/
export type Join<
Strings extends Array<string | number>,
Delimiter extends string,
> = Strings extends [] ? '' :
Strings extends [string | number] ? `${Strings[0]}` :
// @ts-expect-error `Rest` is inferred as `unknown` here: https://github.com/microsoft/TypeScript/issues/45281
Strings extends [string | number, ...infer Rest] ? `${Strings[0]}${Delimiter}${Join<Rest, Delimiter>}` :
string;

90
node_modules/type-fest/source/jsonify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,90 @@
import type {JsonPrimitive, JsonValue} from './basic';
import {Finite, NegativeInfinity, PositiveInfinity} from './numeric';
import {TypedArray} from './typed-array';
// Note: The return value has to be `any` and not `unknown` so it can match `void`.
type NotJsonable = ((...args: any[]) => any) | undefined | symbol;
/**
Transform a type to one that is assignable to the `JsonValue` type.
This includes:
1. Transforming JSON `interface` to a `type` that is assignable to `JsonValue`.
2. Transforming non-JSON value that is *jsonable* to a type that is assignable to `JsonValue`, where *jsonable* means the non-JSON value implements the `.toJSON()` method that returns a value that is assignable to `JsonValue`.
@remarks
An interface cannot be structurally compared to `JsonValue` because an interface can be re-opened to add properties that may not be satisfy `JsonValue`.
@example
```
import type {Jsonify} from 'type-fest';
interface Geometry {
type: 'Point' | 'Polygon';
coordinates: [number, number];
}
const point: Geometry = {
type: 'Point',
coordinates: [1, 1]
};
const problemFn = (data: JsonValue) => {
// Does something with data
};
problemFn(point); // Error: type Geometry is not assignable to parameter of type JsonValue because it is an interface
const fixedFn = <T>(data: Jsonify<T>) => {
// Does something with data
};
fixedFn(point); // Good: point is assignable. Jsonify<T> transforms Geometry into value assignable to JsonValue
fixedFn(new Date()); // Error: As expected, Date is not assignable. Jsonify<T> cannot transforms Date into value assignable to JsonValue
```
Non-JSON values such as `Date` implement `.toJSON()`, so they can be transformed to a value assignable to `JsonValue`:
@example
```
import type {Jsonify} from 'type-fest';
const time = {
timeValue: new Date()
};
// `Jsonify<typeof time>` is equivalent to `{timeValue: string}`
const timeJson = JSON.parse(JSON.stringify(time)) as Jsonify<typeof time>;
```
@link https://github.com/Microsoft/TypeScript/issues/1897#issuecomment-710744173
@category JSON
*/
type Jsonify<T> =
// Check if there are any non-JSONable types represented in the union.
// Note: The use of tuples in this first condition side-steps distributive conditional types
// (see https://github.com/microsoft/TypeScript/issues/29368#issuecomment-453529532)
[Extract<T, NotJsonable | bigint>] extends [never]
? T extends PositiveInfinity | NegativeInfinity ? null
: T extends JsonPrimitive ? T // Primitive is acceptable
: T extends object
// Any object with toJSON is special case
? T extends {toJSON(): infer J} ? (() => J) extends (() => JsonValue) // Is J assignable to JsonValue?
? J // Then T is Jsonable and its Jsonable value is J
: never // Not Jsonable because its toJSON() method does not return JsonValue
// Instanced primitives are objects
: T extends Number ? number
: T extends String ? string
: T extends Boolean ? boolean
: T extends Map<any, any> | Set<any> ? {}
: T extends TypedArray ? Record<string, number>
: T extends any[]
? {[I in keyof T]: T[I] extends NotJsonable ? null : Jsonify<T[I]>}
: {[P in keyof T as P extends symbol ? never
: T[P] extends NotJsonable ? never
: P
]: Jsonify<Required<T>[P]>} // Recursive call for its children
: never // Otherwise any other non-object is removed
: never; // Otherwise non-JSONable type union was found not empty

38
node_modules/type-fest/source/kebab-case.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
import type {DelimiterCase} from './delimiter-case';
/**
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<T> = {
[K in keyof T as KebabCase<K>]: T[K]
};
interface CliOptions {
dryRun: boolean;
includeFile: string;
foo: number;
}
const rawCliOptions: KebabCasedProperties<CliOptions> = {
'dry-run': true,
'include-file': 'bar.js',
foo: 123
};
```
@category Change case
@category Template literal
*/
export type KebabCase<Value> = DelimiterCase<Value, '-'>;

View File

@@ -0,0 +1,47 @@
import type {DelimiterCasedPropertiesDeep} from './delimiter-cased-properties-deep';
/**
Convert object properties to kebab case recursively.
This can be useful when, for example, converting some API types from a different style.
@see KebabCase
@see KebabCasedProperties
@example
```
import type [KebabCasedPropertiesDeep] from 'type-fest';
interface User {
userId: number;
userName: string;
}
interface UserWithFriends {
userInfo: User;
userFriends: User[];
}
const result: KebabCasedPropertiesDeep<UserWithFriends> = {
'user-info': {
'user-id': 1,
'user-name': 'Tom',
},
'user-friends': [
{
'user-id': 2,
'user-name': 'Jerry',
},
{
'user-id': 3,
'user-name': 'Spike',
},
],
};
```
@category Change case
@category Template literal
@category Object
*/
export type KebabCasedPropertiesDeep<Value> = DelimiterCasedPropertiesDeep<Value, '-'>;

View File

@@ -0,0 +1,30 @@
import type {DelimiterCasedProperties} from './delimiter-cased-properties';
/**
Convert object properties to kebab case but not recursively.
This can be useful when, for example, converting some API types from a different style.
@see KebabCase
@see KebabCasedPropertiesDeep
@example
```
import type {KebabCasedProperties} from 'type-fest';
interface User {
userId: number;
userName: string;
}
const result: KebabCasedProperties<User> = {
'user-id': 1,
'user-name': 'Tom',
};
```
@category Change case
@category Template literal
@category Object
*/
export type KebabCasedProperties<Value> = DelimiterCasedProperties<Value, '-'>;

28
node_modules/type-fest/source/last-array-element.d.ts generated vendored Normal file
View File

@@ -0,0 +1,28 @@
/**
Extracts the type of the last element of an array.
Use-case: Defining the return type of functions that extract the last element of an array, for example [`lodash.last`](https://lodash.com/docs/4.17.15#last).
@example
```
import type {LastArrayElement} from 'type-fest';
declare function lastOf<V extends readonly any[]>(array: V): LastArrayElement<V>;
const array = ['foo', 2];
typeof lastOf(array);
//=> number
```
@category Array
@category Template literal
*/
export type LastArrayElement<ValueType extends readonly unknown[]> =
ValueType extends readonly [infer ElementType]
? ElementType
: ValueType extends readonly [infer _, ...infer Tail]
? LastArrayElement<Tail>
: ValueType extends ReadonlyArray<infer ElementType>
? ElementType
: never;

View File

@@ -0,0 +1,36 @@
/**
Given a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) return the {@link Primitive | primitive type} it belongs to, or `never` if it's not a primitive.
Use-case: Working with generic types that may be literal types.
@example
```
import type {LiteralToPrimitive} from 'type-fest';
// No overloads needed to get the correct return type
function plus<T extends number | bigint | string>(x: T, y: T): LiteralToPrimitive<T> {
return x + (y as any);
}
plus('a', 'b'); // string
plus(1, 2); // number
plus(1n, 2n); // bigint
```
@category Type
*/
export type LiteralToPrimitive<T> = T extends number
? number
: T extends bigint
? bigint
: T extends string
? string
: T extends boolean
? boolean
: T extends symbol
? symbol
: T extends null
? null
: T extends undefined
? undefined
: never;

35
node_modules/type-fest/source/literal-union.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import type {Primitive} from './primitive';
/**
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 type LiteralUnion<
LiteralType,
BaseType extends Primitive,
> = LiteralType | (BaseType & Record<never, never>);

41
node_modules/type-fest/source/merge-exclusive.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
// Helper type. Not useful on its own.
type Without<FirstType, SecondType> = {[KeyType in Exclude<keyof FirstType, keyof SecondType>]?: never};
/**
Create a type that has mutually exclusive keys.
This type was inspired by [this comment](https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-373782604).
This type works with a helper type, called `Without`. `Without<FirstType, SecondType>` produces a type that has only keys from `FirstType` which are not present on `SecondType` and sets the value type for these keys to `never`. This helper type is then used in `MergeExclusive` to remove keys from either `FirstType` or `SecondType`.
@example
```
import type {MergeExclusive} from 'type-fest';
interface ExclusiveVariation1 {
exclusive1: boolean;
}
interface ExclusiveVariation2 {
exclusive2: string;
}
type ExclusiveOptions = MergeExclusive<ExclusiveVariation1, ExclusiveVariation2>;
let exclusiveOptions: ExclusiveOptions;
exclusiveOptions = {exclusive1: true};
//=> Works
exclusiveOptions = {exclusive2: 'hi'};
//=> Works
exclusiveOptions = {exclusive1: true, exclusive2: 'hi'};
//=> Error
```
@category Object
*/
export type MergeExclusive<FirstType, SecondType> =
(FirstType | SecondType) extends object ?
(Without<FirstType, SecondType> & SecondType) | (Without<SecondType, FirstType> & FirstType) :
FirstType | SecondType;

27
node_modules/type-fest/source/merge.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import type {Except} from './except';
import type {Simplify} from './simplify';
type Merge_<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
/**
Merge two types into a new type. Keys of the second type overrides keys of the first type.
@example
```
import type {Merge} from 'type-fest';
type Foo = {
a: number;
b: string;
};
type Bar = {
b: number;
};
const ab: Merge<Foo, Bar> = {a: 1, b: 2};
```
@category Object
*/
export type Merge<FirstType, SecondType> = Simplify<Merge_<FirstType, SecondType>>;

View File

@@ -0,0 +1,43 @@
import type {IsEqual, Subtract} from './internal';
type Recursive<T> = Array<Recursive<T>>;
/**
Creates a type that represents a multidimensional array of the given type and dimension.
Use-cases:
- Return a n-dimensional array from functions.
- Declare a n-dimensional array by defining its dimensions rather than declaring `[]` repetitively.
- Infer the dimensions of a n-dimensional array automatically from function arguments.
- Avoid the need to know in advance the dimensions of a n-dimensional array allowing them to be dynamic.
@example
```
import type {MultidimensionalArray} from 'type-fest';
function emptyMatrix<T extends number>(dimensions: T): MultidimensionalArray<unknown, T> {
const matrix: unknown[] = [];
let subMatrix = matrix;
for (let dimension = 1; dimension < dimensions; ++dimension) {
console.log(`Initializing dimension #${dimension}`);
subMatrix[0] = [];
subMatrix = subMatrix[0] as unknown[];
}
return matrix as MultidimensionalArray<unknown, T>;
}
const matrix = emptyMatrix(3);
matrix[0][0][0] = 42;
```
@category Array
*/
export type MultidimensionalArray<Element, Dimensions extends number> = number extends Dimensions
? Recursive<Element>
: IsEqual<Dimensions, 0> extends true
? Element
: Array<MultidimensionalArray<Element, Subtract<Dimensions, 1>>>;

View File

@@ -0,0 +1,47 @@
import type {IsEqual, Subtract} from './internal';
type Recursive<T> = ReadonlyArray<Recursive<T>>;
/**
Creates a type that represents a multidimensional readonly array that of the given type and dimension.
Use-cases:
- Return a n-dimensional array from functions.
- Declare a n-dimensional array by defining its dimensions rather than declaring `[]` repetitively.
- Infer the dimensions of a n-dimensional array automatically from function arguments.
- Avoid the need to know in advance the dimensions of a n-dimensional array allowing them to be dynamic.
@example
```
import type {MultidimensionalReadonlyArray} from 'type-fest';
function emptyMatrix<T extends number>(dimensions: T): MultidimensionalReadonlyArray<unknown, T> {
const matrix: unknown[] = [];
let subMatrix = matrix;
for (let dimension = 1; dimension < dimensions; ++dimension) {
console.log(`Initializing dimension #${dimension}`);
subMatrix[0] = [];
if (dimension < dimensions - 1) {
subMatrix = subMatrix[0] as unknown[];
} else {
subMatrix[0] = 42;
}
}
return matrix as MultidimensionalReadonlyArray<unknown, T>;
}
const matrix = emptyMatrix(3);
const answer = matrix[0][0][0]; // 42
```
@category Array
*/
export type MultidimensionalReadonlyArray<Element, Dimensions extends number> = number extends Dimensions
? Recursive<Element>
: IsEqual<Dimensions, 0> extends true
? Element
: ReadonlyArray<MultidimensionalReadonlyArray<Element, Subtract<Dimensions, 1>>>;

5
node_modules/type-fest/source/mutable.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import type {Writable} from './writable';
/** @deprecated @see Writable */
export type Mutable<BaseType, Keys extends keyof BaseType = keyof BaseType> =
Writable<BaseType, Keys>;

170
node_modules/type-fest/source/numeric.d.ts generated vendored Normal file
View File

@@ -0,0 +1,170 @@
type Numeric = number | bigint;
type Zero = 0 | 0n;
/**
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 type PositiveInfinity = 1e999;
/**
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 type NegativeInfinity = -1e999;
/**
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<T extends number>(length: Finite<T>): void;
```
@category Numeric
*/
export type Finite<T extends number> = T extends PositiveInfinity | NegativeInfinity ? never : T;
/**
A `number` that is an integer.
You can't pass a `bigint` as they are already guaranteed to be integers.
Use-case: Validating and documenting parameters.
@example
```
import type {Integer} from 'type-fest';
declare function setYear<T extends number>(length: Integer<T>): 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 type Integer<T extends number> = `${T}` extends `${bigint}` ? T : never;
/**
A `number` that is not an integer.
You can't pass a `bigint` as they are already guaranteed to be integers.
Use-case: Validating and documenting parameters.
@example
```
import type {Float} from 'type-fest';
declare function setPercentage<T extends number>(length: Float<T>): void;
```
@see Integer
@category Numeric
*/
export type Float<T extends number> = T extends Integer<T> ? never : T;
/**
A negative (`-∞ < x < 0`) `number` that is not an integer.
Equivalent to `Negative<Float<T>>`.
Use-case: Validating and documenting parameters.
@see Negative
@see Float
@category Numeric
*/
export type NegativeFloat<T extends number> = Negative<Float<T>>;
/**
A negative `number`/`bigint` (`-∞ < x < 0`)
Use-case: Validating and documenting parameters.
@see NegativeInteger
@see NonNegative
@category Numeric
*/
export type Negative<T extends Numeric> = T extends Zero ? never : `${T}` extends `-${string}` ? T : never;
/**
A negative (`-∞ < x < 0`) `number` that is an integer.
Equivalent to `Negative<Integer<T>>`.
You can't pass a `bigint` as they are already guaranteed to be integers, instead use `Negative<T>`.
Use-case: Validating and documenting parameters.
@see Negative
@see Integer
@category Numeric
*/
export type NegativeInteger<T extends number> = Negative<Integer<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<T extends number>(length: NonNegative<T>): void;
```
@category Numeric
*/
export type NonNegative<T extends Numeric> = T extends Zero ? T : Negative<T> extends never ? T : never;
/**
A non-negative (`0 <= x < ∞`) `number` that is an integer.
Equivalent to `NonNegative<Integer<T>>`.
You can't pass a `bigint` as they are already guaranteed to be integers, instead use `NonNegative<T>`.
Use-case: Validating and documenting parameters.
@see NonNegative
@see Integer
@example
```
import type {NonNegativeInteger} from 'type-fest';
declare function setLength<T extends number>(length: NonNegativeInteger<T>): void;
```
@category Numeric
*/
export type NonNegativeInteger<T extends number> = NonNegative<Integer<T>>;

62
node_modules/type-fest/source/observable-like.d.ts generated vendored Normal file
View File

@@ -0,0 +1,62 @@
declare global {
interface SymbolConstructor {
readonly observable: symbol;
}
}
/**
@remarks
The TC39 observable proposal defines a `closed` property, but some implementations (such as xstream) do not as of 10/08/2021.
As well, some guideance on making an `Observable` do not include `closed` propery.
@see https://github.com/tc39/proposal-observable/blob/master/src/Observable.js#L129-L130
@see https://github.com/staltz/xstream/blob/6c22580c1d84d69773ee4b0905df44ad464955b3/src/index.ts#L79-L85
@see https://github.com/benlesh/symbol-observable#making-an-object-observable
@category Observable
*/
export type Unsubscribable = {
unsubscribe(): void;
};
/**
@category Observable
*/
type OnNext<ValueType> = (value: ValueType) => void;
/**
@category Observable
*/
type OnError = (error: unknown) => void;
/**
@category Observable
*/
type OnComplete = () => void;
/**
@category Observable
*/
export type Observer<ValueType> = {
next: OnNext<ValueType>;
error: OnError;
complete: OnComplete;
};
/**
Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
@remarks
The TC39 Observable proposal defines 2 forms of `subscribe()`:
1. Three callback arguments: `subscribe(observer: OnNext<ValueType>, onError?: OnError, onComplete?: OnComplete): Unsubscribable;`
2. A single `observer` argument: (as defined below)
But `Observable` implementations have evolved to preferring case 2 and some implementations choose not to implement case 1. Therefore, an `ObservableLike` cannot be trusted to implement the first case. (xstream and hand built observerables often do not implement case 1)
@see https://github.com/tc39/proposal-observable#observable
@see https://github.com/tc39/proposal-observable/blob/master/src/Observable.js#L246-L259
@see https://benlesh.com/posts/learning-observable-by-building-observable/
@category Observable
*/
export interface ObservableLike<ValueType = unknown> {
subscribe(observer?: Partial<Observer<ValueType>>): Unsubscribable;
[Symbol.observable](): ObservableLike<ValueType>;
}

107
node_modules/type-fest/source/opaque.d.ts generated vendored Normal file
View File

@@ -0,0 +1,107 @@
declare const tag: unique symbol;
declare type Tagged<Token> = {
readonly [tag]: Token;
};
/**
Create an opaque type, which hides its internal details from the public, and can only be created by being used explicitly.
The generic type parameter can be anything. It doesn't have to be an object.
[Read more about opaque types.](https://codemix.com/opaque-types-in-javascript/)
There have been several discussions about adding this feature to TypeScript via the `opaque type` operator, similar to how Flow does it. Unfortunately, nothing has (yet) moved forward:
- [Microsoft/TypeScript#202](https://github.com/microsoft/TypeScript/issues/202)
- [Microsoft/TypeScript#15408](https://github.com/Microsoft/TypeScript/issues/15408)
- [Microsoft/TypeScript#15807](https://github.com/Microsoft/TypeScript/issues/15807)
@example
```
import type {Opaque} from 'type-fest';
type AccountNumber = Opaque<number, 'AccountNumber'>;
type AccountBalance = Opaque<number, 'AccountBalance'>;
// The `Token` parameter allows the compiler to differentiate between types, whereas "unknown" will not. For example, consider the following structures:
type ThingOne = Opaque<string>;
type ThingTwo = Opaque<string>;
// To the compiler, these types are allowed to be cast to each other as they have the same underlying type. They are both `string & { __opaque__: unknown }`.
// To avoid this behaviour, you would instead pass the "Token" parameter, like so.
type NewThingOne = Opaque<string, 'ThingOne'>;
type NewThingTwo = Opaque<string, 'ThingTwo'>;
// Now they're completely separate types, so the following will fail to compile.
function createNewThingOne (): NewThingOne {
// As you can see, casting from a string is still allowed. However, you may not cast NewThingOne to NewThingTwo, and vice versa.
return 'new thing one' as NewThingOne;
}
// This will fail to compile, as they are fundamentally different types.
const thingTwo = createNewThingOne() as NewThingTwo;
// Here's another example of opaque typing.
function createAccountNumber(): AccountNumber {
return 2 as AccountNumber;
}
function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance {
return 4 as AccountBalance;
}
// This will compile successfully.
getMoneyForAccount(createAccountNumber());
// But this won't, because it has to be explicitly passed as an `AccountNumber` type.
getMoneyForAccount(2);
// You can use opaque values like they aren't opaque too.
const accountNumber = createAccountNumber();
// This will not compile successfully.
const newAccountNumber = accountNumber + 2;
// As a side note, you can (and should) use recursive types for your opaque types to make them stronger and hopefully easier to type.
type Person = {
id: Opaque<number, Person>;
name: string;
};
```
@category Type
*/
export type Opaque<Type, Token = unknown> = Type & Tagged<Token>;
/**
Revert an opaque type back to its original type by removing the readonly `[tag]`.
Why is this necessary?
1. Use an `Opaque` type as object keys
2. Prevent TS4058 error: "Return type of exported function has or is using name X from external module Y but cannot be named"
@example
```
import type {Opaque, UnwrapOpaque} from 'type-fest';
type AccountType = Opaque<'SAVINGS' | 'CHECKING', 'AccountType'>;
const moneyByAccountType: Record<UnwrapOpaque<AccountType>, number> = {
SAVINGS: 99,
CHECKING: 0.1
};
// Without UnwrapOpaque, the following expression would throw a type error.
const money = moneyByAccountType.SAVINGS; // TS error: Property 'SAVINGS' does not exist
// Attempting to pass an non-Opaque type to UnwrapOpaque will raise a type error.
type WontWork = UnwrapOpaque<string>;
```
@category Type
*/
export type UnwrapOpaque<OpaqueType extends Tagged<unknown>> =
OpaqueType extends Opaque<infer Type, OpaqueType[typeof tag]>
? Type
: OpaqueType;

38
node_modules/type-fest/source/optional-keys-of.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
/**
Extract all optional keys from the given type.
This is useful when you want to create a new type that contains different type values for the optional keys only.
@example
```
import type {OptionalKeysOf, Except} from 'type-fest';
interface User {
name: string;
surname: string;
luckyNumber?: number;
}
const REMOVE_FIELD = Symbol('remove field symbol');
type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
[Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
};
const update1: UpdateOperation<User> = {
name: 'Alice'
};
const update2: UpdateOperation<User> = {
name: 'Bob',
luckyNumber: REMOVE_FIELD
};
```
@category Utilities
*/
export type OptionalKeysOf<BaseType extends object> = Exclude<{
[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
? never
: Key
}[keyof BaseType], undefined>;

663
node_modules/type-fest/source/package-json.d.ts generated vendored Normal file
View File

@@ -0,0 +1,663 @@
import type {LiteralUnion} from './literal-union';
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 interface DirectoryLocations {
[directoryType: string]: unknown;
/**
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<Record<string, string>>;
/**
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<Record<string, string>>;
/**
Conditions which provide a way to resolve a package entry point based on the environment.
*/
export type ExportCondition = LiteralUnion<
| 'import'
| 'require'
| 'node'
| 'node-addons'
| 'deno'
| 'browser'
| 'electron'
| 'react-native'
| 'default',
string
>;
type ExportConditions = {[condition in ExportCondition]: Exports};
/**
Entry points of a module, optionally with conditions and subpath exports.
*/
export type Exports =
| null
| string
| Array<string | ExportConditions>
| ExportConditions
| {[path: string]: Exports}; // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
/**
Import map entries of a module, optionally with conditions.
*/
export type Imports = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
[key: string]: string | {[key in ExportCondition]: Exports};
};
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<Record<string, string | false>>;
/**
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 interface TypeScriptConfiguration {
/**
Location of the bundled TypeScript declaration file.
*/
types?: string;
/**
Version selection map of TypeScript.
*/
typesVersions?: Partial<Record<string, Partial<Record<string, string[]>>>>;
/**
Location of the bundled TypeScript declaration file. Alias of `types`.
*/
typings?: string;
}
/**
An alternative configuration for Yarn workspaces.
*/
export interface 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.
[Read more](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/)
*/
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`.
*/
type WorkspacePattern = string;
export interface YarnConfiguration {
/**
Used to configure [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 `yarn install` once 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;
/**
If your package only allows one version of a given dependency, and youd 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 interface 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.
*/
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<Record<string, string>>;
/**
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?: Record<string, unknown>;
/**
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<Record<string, {optional: true}>>;
/**
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<LiteralUnion<
| 'aix'
| 'darwin'
| 'freebsd'
| 'linux'
| 'openbsd'
| 'sunos'
| 'win32'
| '!aix'
| '!darwin'
| '!freebsd'
| '!linux'
| '!openbsd'
| '!sunos'
| '!win32',
string
>>;
/**
CPU architectures the module runs on.
*/
cpu?: Array<LiteralUnion<
| 'arm'
| 'arm64'
| 'ia32'
| 'mips'
| 'mipsel'
| 'ppc'
| 'ppc64'
| 's390'
| 's390x'
| 'x32'
| 'x64'
| '!arm'
| '!arm64'
| '!ia32'
| '!mips'
| '!mipsel'
| '!ppc'
| '!ppc64'
| '!s390'
| '!s390x'
| '!x32'
| '!x64',
string
>>;
/**
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;
};
}
export interface PublishConfig {
/**
Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig).
*/
[additionalProperties: string]: unknown;
/**
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 type PackageJson =
PackageJson.PackageJsonStandard &
PackageJson.NonStandardEntryPoints &
PackageJson.TypeScriptConfiguration &
PackageJson.YarnConfiguration &
PackageJson.JSPMConfiguration;

113
node_modules/type-fest/source/partial-deep.d.ts generated vendored Normal file
View File

@@ -0,0 +1,113 @@
import type {BuiltIns} from './internal';
/**
@see PartialDeep
*/
export interface PartialDeepOptions {
/**
Whether to affect the individual elements of arrays and tuples.
@default true
*/
readonly recurseIntoArrays?: boolean;
}
/**
Create a type from another type with all keys and nested keys set to optional.
Use-cases:
- Merging a default settings/config object with another object, the second object would be a deep partial of the default object.
- Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test.
@example
```
import type {PartialDeep} from 'type-fest';
const settings: Settings = {
textEditor: {
fontSize: 14;
fontColor: '#000000';
fontWeight: 400;
}
autocomplete: false;
autosave: true;
};
const applySavedSettings = (savedSettings: PartialDeep<Settings>) => {
return {...settings, ...savedSettings};
}
settings = applySavedSettings({textEditor: {fontWeight: 500}});
```
By default, this also affects array and tuple types:
```
import type {PartialDeep} from 'type-fest';
interface Settings {
languages: string[];
}
const partialSettings: PartialDeep<Settings> = {
languages: [undefined]
};
```
If this is undesirable, you can pass `{recurseIntoArrays: false}` as the second type argument.
@category Object
@category Array
@category Set
@category Map
*/
export type PartialDeep<T, Options extends PartialDeepOptions = {}> = T extends BuiltIns
? T
: T extends Map<infer KeyType, infer ValueType>
? PartialMapDeep<KeyType, ValueType, Options>
: T extends Set<infer ItemType>
? PartialSetDeep<ItemType, Options>
: T extends ReadonlyMap<infer KeyType, infer ValueType>
? PartialReadonlyMapDeep<KeyType, ValueType, Options>
: T extends ReadonlySet<infer ItemType>
? PartialReadonlySetDeep<ItemType, Options>
: T extends ((...arguments: any[]) => unknown)
? T | undefined
: T extends object
? T extends ReadonlyArray<infer ItemType> // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156
? Options['recurseIntoArrays'] extends false // If they opt out of array testing, just use the original type
? T
: ItemType[] extends T // Test for arrays (non-tuples) specifically
? readonly ItemType[] extends T // Differentiate readonly and mutable arrays
? ReadonlyArray<PartialDeep<ItemType | undefined, Options>>
: Array<PartialDeep<ItemType | undefined, Options>>
: PartialObjectDeep<T, Options> // Tuples behave properly
: PartialObjectDeep<T, Options>
: unknown;
/**
Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`.
*/
interface PartialMapDeep<KeyType, ValueType, Options extends PartialDeepOptions> extends Map<PartialDeep<KeyType, Options>, PartialDeep<ValueType, Options>> {}
/**
Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`.
*/
interface PartialSetDeep<T, Options extends PartialDeepOptions> extends Set<PartialDeep<T, Options>> {}
/**
Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`.
*/
interface PartialReadonlyMapDeep<KeyType, ValueType, Options extends PartialDeepOptions> extends ReadonlyMap<PartialDeep<KeyType, Options>, PartialDeep<ValueType, Options>> {}
/**
Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`.
*/
interface PartialReadonlySetDeep<T, Options extends PartialDeepOptions> extends ReadonlySet<PartialDeep<T, Options>> {}
/**
Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`.
*/
type PartialObjectDeep<ObjectType extends object, Options extends PartialDeepOptions> = {
[KeyType in keyof ObjectType]?: PartialDeep<ObjectType[KeyType], Options>
};

View File

@@ -0,0 +1,70 @@
import type {BuiltIns} from './internal';
import type {Merge} from './merge';
/**
@see PartialOnUndefinedDeep
*/
export interface PartialOnUndefinedDeepOptions {
/**
Whether to affect the individual elements of arrays and tuples.
@default false
*/
readonly recurseIntoArrays?: boolean;
}
/**
Create a deep version of another type where all keys accepting `undefined` type are set to optional.
This utility type is recursive, transforming at any level deep. By default, it does not affect arrays and tuples items unless you explicitly pass `{recurseIntoArrays: true}` as the second type argument.
Use-cases:
- Make all properties of a type that can be undefined optional to not have to specify keys with undefined value.
@example
```
import type {PartialOnUndefinedDeep} from 'type-fest';
interface Settings {
optionA: string;
optionB: number | undefined;
subOption: {
subOptionA: boolean;
subOptionB: boolean | undefined;
}
};
const testSettings: PartialOnUndefinedDeep<Settings> = {
optionA: 'foo',
// 👉 optionB is now optional and can be omitted
subOption: {
subOptionA: true,
// 👉 subOptionB is now optional as well and can be omitted
},
};
```
@category Object
*/
export type PartialOnUndefinedDeep<T, Options extends PartialOnUndefinedDeepOptions = {}> = T extends Record<any, any> | undefined
? {[KeyType in keyof T as undefined extends T[KeyType] ? KeyType : never]?: PartialOnUndefinedDeepValue<T[KeyType], Options>} extends infer U // Make a partial type with all value types accepting undefined (and set them optional)
? Merge<{[KeyType in keyof T as KeyType extends keyof U ? never : KeyType]: PartialOnUndefinedDeepValue<T[KeyType], Options>}, U> // Join all remaining keys not treated in U
: never // Should not happen
: T;
/**
Utility type to get the value type by key and recursively call `PartialOnUndefinedDeep` to transform sub-objects.
*/
type PartialOnUndefinedDeepValue<T, Options extends PartialOnUndefinedDeepOptions> = T extends BuiltIns | ((...arguments: any[]) => unknown)
? T
: T extends ReadonlyArray<infer U> // Test if type is array or tuple
? Options['recurseIntoArrays'] extends true // Check if option is activated
? U[] extends T // Check if array not tuple
? readonly U[] extends T
? ReadonlyArray<PartialOnUndefinedDeep<U, Options>> // Readonly array treatment
: Array<PartialOnUndefinedDeep<U, Options>> // Mutable array treatment
: PartialOnUndefinedDeep<{[Key in keyof T]: PartialOnUndefinedDeep<T[Key], Options>}, Options> // Tuple treatment
: T
: T extends Record<any, any> | undefined
? PartialOnUndefinedDeep<T, Options>
: unknown;

38
node_modules/type-fest/source/pascal-case.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
import type {CamelCase} from './camel-case';
/**
Converts a string literal to pascal-case.
@example
```
import type {PascalCase} from 'type-fest';
// Simple
const someVariable: PascalCase<'foo-bar'> = 'FooBar';
// Advanced
type PascalCaseProps<T> = {
[K in keyof T as PascalCase<K>]: T[K]
};
interface RawOptions {
'dry-run': boolean;
'full_family_name': string;
foo: number;
}
const dbResult: CamelCasedProperties<ModelProps> = {
DryRun: true,
FullFamilyName: 'bar.js',
Foo: 123
};
```
@category Change case
@category Template literal
*/
export type PascalCase<Value> = CamelCase<Value> extends string
? Capitalize<CamelCase<Value>>
: CamelCase<Value>;

View File

@@ -0,0 +1,54 @@
import type {PascalCase} from './pascal-case';
/**
Convert object properties to pascal case recursively.
This can be useful when, for example, converting some API types from a different style.
@see PascalCase
@see PascalCasedProperties
@example
```
import type {PascalCasedPropertiesDeep} from 'type-fest';
interface User {
userId: number;
userName: string;
}
interface UserWithFriends {
userInfo: User;
userFriends: User[];
}
const result: PascalCasedPropertiesDeep<UserWithFriends> = {
UserInfo: {
UserId: 1,
UserName: 'Tom',
},
UserFriends: [
{
UserId: 2,
UserName: 'Jerry',
},
{
UserId: 3,
UserName: 'Spike',
},
],
};
```
@category Change case
@category Template literal
@category Object
*/
export type PascalCasedPropertiesDeep<Value> = Value extends Function | Date | RegExp
? Value
: Value extends Array<infer U>
? Array<PascalCasedPropertiesDeep<U>>
: Value extends Set<infer U>
? Set<PascalCasedPropertiesDeep<U>> : {
[K in keyof Value as PascalCase<K>]: PascalCasedPropertiesDeep<Value[K]>;
};

View File

@@ -0,0 +1,34 @@
import type {PascalCase} from './pascal-case';
/**
Convert object properties to pascal case but not recursively.
This can be useful when, for example, converting some API types from a different style.
@see PascalCase
@see PascalCasedPropertiesDeep
@example
```
import type {PascalCasedProperties} from 'type-fest';
interface User {
userId: number;
userName: string;
}
const result: PascalCasedProperties<User> = {
UserId: 1,
UserName: 'Tom',
};
```
@category Change case
@category Template literal
@category Object
*/
export type PascalCasedProperties<Value> = Value extends Function
? Value
: Value extends Array<infer U>
? Value
: {[K in keyof Value as PascalCase<K>]: Value[K]};

13
node_modules/type-fest/source/primitive.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/**
Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
@category Type
*/
export type Primitive =
| null
| undefined
| string
| number
| boolean
| symbol
| bigint;

25
node_modules/type-fest/source/promisable.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/**
Create a type that represents either the value or the value wrapped in `PromiseLike`.
Use-cases:
- A function accepts a callback that may either return a value synchronously or may return a promised value.
- This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript.
@example
```
import type {Promisable} from 'type-fest';
async function logger(getLogEntry: () => Promisable<string>): Promise<void> {
const entry = await getLogEntry();
console.log(entry);
}
logger(() => 'foo');
logger(() => Promise.resolve('bar'));
```
@category Async
*/
export type Promisable<T> = T | PromiseLike<T>;

29
node_modules/type-fest/source/promise-value.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
@deprecated Use the built-in [`Awaited` type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#the-awaited-type-and-promise-improvements) instead.
Returns the type that is wrapped inside a `Promise` type.
If the type is a nested Promise, it is unwrapped recursively until a non-Promise type is obtained.
If the type is not a `Promise`, the type itself is returned.
@example
```
import type {PromiseValue} from 'type-fest';
type AsyncData = Promise<string>;
let asyncData: AsyncData = Promise.resolve('ABC');
type Data = PromiseValue<AsyncData>;
let data: Data = await asyncData;
// Here's an example that shows how this type reacts to non-Promise types.
type SyncData = PromiseValue<string>;
let syncData: SyncData = getSyncData();
// Here's an example that shows how this type reacts to recursive Promise types.
type RecursiveAsyncData = Promise<Promise<string>>;
let recursiveAsyncData: PromiseValue<RecursiveAsyncData> = await Promise.resolve(Promise.resolve('ABC'));
```
@category Async
*/
export type PromiseValue<PromiseType> = PromiseType extends PromiseLike<infer Value> ? PromiseValue<Value> : PromiseType;

85
node_modules/type-fest/source/readonly-deep.d.ts generated vendored Normal file
View File

@@ -0,0 +1,85 @@
import type {BuiltIns} from './internal';
/**
Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively.
This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/13923) if you want to have this type as a built-in in TypeScript.
@example
```
// data.json
{
"foo": ["bar"]
}
// main.ts
import type {ReadonlyDeep} from 'type-fest';
import dataJson = require('./data.json');
const data: ReadonlyDeep<typeof dataJson> = dataJson;
export default data;
// test.ts
import data from './main';
data.foo.push('bar');
//=> error TS2339: Property 'push' does not exist on type 'readonly string[]'
```
@category Object
@category Array
@category Set
@category Map
*/
export type ReadonlyDeep<T> = T extends BuiltIns
? T
: T extends (...arguments: any[]) => unknown
? {} extends ReadonlyObjectDeep<T>
? T
: HasMultipleCallSignatures<T> extends true
? T
: ((...arguments: Parameters<T>) => ReturnType<T>) & ReadonlyObjectDeep<T>
: T extends Readonly<ReadonlyMap<infer KeyType, infer ValueType>>
? ReadonlyMapDeep<KeyType, ValueType>
: T extends Readonly<ReadonlySet<infer ItemType>>
? ReadonlySetDeep<ItemType>
: T extends object
? ReadonlyObjectDeep<T>
: unknown;
/**
Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`.
*/
interface ReadonlyMapDeep<KeyType, ValueType>
extends Readonly<ReadonlyMap<ReadonlyDeep<KeyType>, ReadonlyDeep<ValueType>>> {}
/**
Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`.
*/
interface ReadonlySetDeep<ItemType>
extends Readonly<ReadonlySet<ReadonlyDeep<ItemType>>> {}
/**
Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`.
*/
type ReadonlyObjectDeep<ObjectType extends object> = {
readonly [KeyType in keyof ObjectType]: ReadonlyDeep<ObjectType[KeyType]>
};
/**
Test if the given function has multiple call signatures.
Needed to handle the case of a single call signature with properties.
Multiple call signatures cannot currently be supported due to a TypeScript limitation.
@see https://github.com/microsoft/TypeScript/issues/29732
*/
type HasMultipleCallSignatures<T extends (...arguments: any[]) => unknown> =
T extends {(...arguments: infer A): unknown; (...arguments: any[]): unknown}
? unknown[] extends A
? false
: true
: false;

41
node_modules/type-fest/source/readonly-tuple.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
/**
Creates a read-only tuple of type `Element` and with the length of `Length`.
@private
@see `ReadonlyTuple` which is safer because it tests if `Length` is a specific finite number.
*/
type BuildTupleHelper<Element, Length extends number, Rest extends Element[]> =
Rest['length'] extends Length ?
readonly [...Rest] : // Terminate with readonly array (aka tuple)
BuildTupleHelper<Element, Length, [Element, ...Rest]>;
/**
Create a type that represents a read-only tuple of the given type and length.
Use-cases:
- Declaring fixed-length tuples 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 a tuple of coordinates with a static length, for example, length of 3 for a 3D vector.
@example
```
import {ReadonlyTuple} from 'type-fest';
type FencingTeam = ReadonlyTuple<string, 3>;
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 Utilities
*/
export type ReadonlyTuple<Element, Length extends number> =
number extends Length
// Because `Length extends number` and `number extends Length`, then `Length` is not a specific finite number.
? readonly Element[] // It's not fixed length.
: BuildTupleHelper<Element, Length, []>; // Otherwise it is a fixed length tuple.

View File

@@ -0,0 +1,104 @@
/**
Remove any index signatures from the given object type, so that only explicitly defined properties remain.
Use-cases:
- Remove overly permissive signatures from third-party types.
This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`.
(The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
```
const indexed: Record<string, unknown> = {}; // Allowed
const keyed: Record<'foo', unknown> = {}; // Error
// => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
```
Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another:
```
type Indexed = {} extends Record<string, unknown>
? '✅ `{}` is assignable to `Record<string, unknown>`'
: '❌ `{}` is NOT assignable to `Record<string, unknown>`';
// => '✅ `{}` is assignable to `Record<string, unknown>`'
type Keyed = {} extends Record<'foo' | 'bar', unknown>
? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`"
: "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`";
// => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"
```
Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`...
```
import type {RemoveIndexSignature} from 'type-fest';
type RemoveIndexSignature<ObjectType> = {
[KeyType in keyof ObjectType // Map each key of `ObjectType`...
]: ObjectType[KeyType]; // ...to its original value, i.e. `RemoveIndexSignature<Foo> == Foo`.
};
```
...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
```
import type {RemoveIndexSignature} from 'type-fest';
type RemoveIndexSignature<ObjectType> = {
[KeyType in keyof ObjectType
// Is `{}` assignable to `Record<KeyType, unknown>`?
as {} extends Record<KeyType, unknown>
? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>`
: ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
]: ObjectType[KeyType];
};
```
If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it.
```
import type {RemoveIndexSignature} from 'type-fest';
type RemoveIndexSignature<ObjectType> = {
[KeyType in keyof ObjectType
as {} extends Record<KeyType, unknown>
? never // => Remove this `KeyType`.
: KeyType // => Keep this `KeyType` as it is.
]: ObjectType[KeyType];
};
```
@example
```
import type {RemoveIndexSignature} from 'type-fest';
interface Example {
// These index signatures will be removed.
[x: string]: any
[x: number]: any
[x: symbol]: any
[x: `head-${string}`]: string
[x: `${string}-tail`]: string
[x: `head-${string}-tail`]: string
[x: `${bigint}`]: string
[x: `embedded-${number}`]: string
// These explicitly defined keys will remain.
foo: 'bar';
qux?: 'baz';
}
type ExampleWithoutIndexSignatures = RemoveIndexSignature<Example>;
// => { foo: 'bar'; qux?: 'baz' | undefined; }
```
@category Object
*/
export type RemoveIndexSignature<ObjectType> = {
[KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
? never
: KeyType]: ObjectType[KeyType];
};

67
node_modules/type-fest/source/replace.d.ts generated vendored Normal file
View File

@@ -0,0 +1,67 @@
type ReplaceOptions = {
all?: boolean;
};
/**
Represents a string with some or all matches replaced by a replacement.
Use-case:
- `snake-case-path` to `dotted.path.notation`
- Changing date/time format: `01-08-2042` → `01/08/2042`
- Manipulation of type properties, for example, removal of prefixes
@example
```
import {Replace} from 'type-fest';
declare function replace<
Input extends string,
Search extends string,
Replacement extends string
>(
input: Input,
search: Search,
replacement: Replacement
): Replace<Input, Search, Replacement>;
declare function replaceAll<
Input extends string,
Search extends string,
Replacement extends string
>(
input: Input,
search: Search,
replacement: Replacement
): Replace<Input, Search, Replacement, {all: true}>;
// The return type is the exact string literal, not just `string`.
replace('hello ?', '?', '🦄');
//=> 'hello 🦄'
replace('hello ??', '?', '❓');
//=> 'hello ❓?'
replaceAll('10:42:00', ':', '-');
//=> '10-42-00'
replaceAll('__userName__', '__', '');
//=> 'userName'
replaceAll('My Cool Title', ' ', '');
//=> 'MyCoolTitle'
```
@category String
@category Template literal
*/
export type Replace<
Input extends string,
Search extends string,
Replacement extends string,
Options extends ReplaceOptions = {},
> = Input extends `${infer Head}${Search}${infer Tail}`
? Options['all'] extends true
? `${Head}${Replacement}${Replace<Tail, Search, Replacement, Options>}`
: `${Head}${Replacement}${Tail}`
: Input;

36
node_modules/type-fest/source/require-all-or-none.d.ts generated vendored Normal file
View File

@@ -0,0 +1,36 @@
/**
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<Responder, 'text' | 'json'> = {
secure: true
};
const responder2: RequireAllOrNone<Responder, 'text' | 'json'> = {
text: () => '{"message": "hi"}',
json: () => '{"message": "ok"}',
secure: true
};
```
@category Object
*/
export type RequireAllOrNone<ObjectType, KeysType extends keyof ObjectType = never> = (
| Required<Pick<ObjectType, KeysType>> // Require all of the given keys.
| Partial<Record<KeysType, never>> // Require none of the given keys.
) &
Omit<ObjectType, KeysType>; // The rest of the keys.

View File

@@ -0,0 +1,35 @@
import type {Except} from './except';
/**
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<Responder, 'text' | 'json'> = {
json: () => '{"message": "ok"}',
secure: true
};
```
@category Object
*/
export type RequireAtLeastOne<
ObjectType,
KeysType extends keyof ObjectType = keyof ObjectType,
> = {
// For each `Key` in `KeysType` make a mapped type:
[Key in KeysType]-?: Required<Pick<ObjectType, Key>> & // 1. Make `Key`'s type required
// 2. Make all other keys in `KeysType` optional
Partial<Pick<ObjectType, Exclude<KeysType, Key>>>;
}[KeysType] &
// 3. Add the remaining keys not in `KeysType`
Except<ObjectType, KeysType>;

34
node_modules/type-fest/source/require-exactly-one.d.ts generated vendored Normal file
View File

@@ -0,0 +1,34 @@
/**
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<Responder, 'text' | 'json'> = {
// Adding a `text` key here would cause a compile error.
json: () => '{"message": "ok"}',
secure: true
};
```
@category Object
*/
export type RequireExactlyOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
{[Key in KeysType]: (
Required<Pick<ObjectType, Key>> &
Partial<Record<Exclude<KeysType, Key>, never>>
)}[KeysType] & Omit<ObjectType, KeysType>;

29
node_modules/type-fest/source/required-keys-of.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
Extract all required keys from the given type.
This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc...
@example
```
import type {RequiredKeysOf} from 'type-fest';
declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn;
interface User {
name: string;
surname: string;
luckyNumber?: number;
}
const validator1 = createValidation<User>('name', value => value.length < 25);
const validator2 = createValidation<User>('surname', value => value.length < 25);
```
@category Utilities
*/
export type RequiredKeysOf<BaseType extends object> = Exclude<{
[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
? Key
: never
}[keyof BaseType], undefined>;

72
node_modules/type-fest/source/schema.d.ts generated vendored Normal file
View File

@@ -0,0 +1,72 @@
/**
Create a deep version of another object type where property values are recursively replaced into a given value type.
Use-cases:
- Form validation: Define how each field should be validated.
- Form settings: Define configuration for input fields.
- Parsing: Define types that specify special behavior for specific fields.
@example
```
import type {Schema} from 'type-fest';
interface User {
id: string;
name: {
firstname: string;
lastname: string;
};
created: Date;
active: boolean;
passwordHash: string;
}
type UserMask = Schema<User, 'mask' | 'hide' | 'show'>;
const userMaskSettings: UserMask = {
id: 'show',
name: {
firstname: 'show',
lastname: 'mask',
},
phoneNumbers: 'mask',
created: 'show',
active: 'show',
passwordHash: 'hide',
}
```
@category Object
*/
export type Schema<ObjectType, ValueType> = ObjectType extends string
? ValueType
: ObjectType extends Map<unknown, unknown>
? ValueType
: ObjectType extends Set<unknown>
? ValueType
: ObjectType extends ReadonlyMap<unknown, unknown>
? ValueType
: ObjectType extends ReadonlySet<unknown>
? ValueType
: ObjectType extends readonly unknown[]
? ValueType
: ObjectType extends unknown[]
? ValueType
: ObjectType extends (...arguments: unknown[]) => unknown
? ValueType
: ObjectType extends Date
? ValueType
: ObjectType extends Function
? ValueType
: ObjectType extends RegExp
? ValueType
: ObjectType extends object
? SchemaObject<ObjectType, ValueType>
: ValueType;
/**
Same as `Schema`, but accepts only `object`s as inputs. Internal helper for `Schema`.
*/
type SchemaObject<ObjectType extends object, K> = {
[KeyType in keyof ObjectType]: Schema<ObjectType[KeyType], K> | K;
};

View File

@@ -0,0 +1,33 @@
import type {SplitIncludingDelimiters} from './delimiter-case';
import type {SnakeCase} from './snake-case';
import type {Includes} from './includes';
/**
Returns a boolean for whether the string is screaming snake case.
*/
type IsScreamingSnakeCase<Value extends string> = Value extends Uppercase<Value>
? Includes<SplitIncludingDelimiters<Lowercase<Value>, '_'>, '_'> extends true
? true
: false
: false;
/**
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 type ScreamingSnakeCase<Value> = Value extends string
? IsScreamingSnakeCase<Value> extends true
? Value
: Uppercase<SnakeCase<Value>>
: Value;

35
node_modules/type-fest/source/set-non-nullable.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import type {Except} from './except';
import type {Simplify} from './simplify';
/**
Create a type that makes the given keys non-nullable. The remaining keys are kept as is.
Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are non-nullable.
@example
```
import type {SetNonNullable} from 'type-fest';
type Foo = {
a: number;
b: string | undefined;
c?: boolean | null;
}
type SomeNonNullable = SetNonNullable<Foo, 'b' | 'c'>;
// type SomeNonNullable = {
// a: number;
// b: string; // Can no longer be undefined.
// c?: boolean; // Can no longer be null, but is still optional.
// }
```
@category Object
*/
export type SetNonNullable<BaseType, Keys extends keyof BaseType> =
Simplify<
// Pick just the keys that are readonly from the base type.
Except<BaseType, Keys> &
// Pick the keys that should be non-nullable from the base type and make them non-nullable.
{[Key in Keys]: NonNullable<BaseType[Key]>}
>;

35
node_modules/type-fest/source/set-optional.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import type {Except} from './except';
import type {Simplify} from './simplify';
/**
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<Foo, 'b' | 'c'>;
// type SomeOptional = {
// a: number;
// b?: string; // Was already optional and still is.
// c?: boolean; // Is now optional.
// }
```
@category Object
*/
export type SetOptional<BaseType, Keys extends keyof BaseType> =
Simplify<
// Pick just the keys that are readonly from the base type.
Except<BaseType, Keys> &
// Pick the keys that should be mutable from the base type and make them mutable.
Partial<Pick<BaseType, Keys>>
>;

35
node_modules/type-fest/source/set-required.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import type {Except} from './except';
import type {Simplify} from './simplify';
/**
Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type.
Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required.
@example
```
import type {SetRequired} from 'type-fest';
type Foo = {
a?: number;
b: string;
c?: boolean;
}
type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
// type SomeRequired = {
// a?: number;
// b: string; // Was already required and still is.
// c: boolean; // Is now required.
// }
```
@category Object
*/
export type SetRequired<BaseType, Keys extends keyof BaseType> =
Simplify<
// Pick just the keys that are optional from the base type.
Except<BaseType, Keys> &
// Pick the keys that should be required from the base type and make them required.
Required<Pick<BaseType, Keys>>
>;

31
node_modules/type-fest/source/set-return-type.d.ts generated vendored Normal file
View File

@@ -0,0 +1,31 @@
type IsAny<T> = 0 extends (1 & T) ? true : false; // https://stackoverflow.com/a/49928360/3406963
type IsNever<T> = [T] extends [never] ? true : false;
type IsUnknown<T> = IsNever<T> extends false ? T extends unknown ? unknown extends T ? IsAny<T> extends false ? true : false : false : false : false;
/**
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<MyFunctionThatCanThrow, SomeOtherType | undefined>;
//=> type MyWrappedFunction = (foo: SomeType, bar: unknown) => SomeOtherType | undefined;
```
@category Function
*/
export type SetReturnType<Fn extends (...args: any[]) => any, TypeToReturn> =
// Just using `Parameters<Fn>` isn't ideal because it doesn't handle the `this` fake parameter.
Fn extends (this: infer ThisArg, ...args: 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<ThisArg> extends true ? (...args: Arguments) => TypeToReturn : (this: ThisArg, ...args: Arguments) => TypeToReturn
) : (
// This part should be unreachable, but we make it meaningful just in case…
(...args: Parameters<Fn>) => TypeToReturn
);

83
node_modules/type-fest/source/simplify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,83 @@
/**
@see Simplify
*/
export interface SimplifyOptions {
/**
Do the simplification recursively.
@default false
*/
deep?: boolean;
}
// Flatten a type without worrying about the result.
type Flatten<
AnyType,
Options extends SimplifyOptions = {},
> = Options['deep'] extends true
? {[KeyType in keyof AnyType]: Simplify<AnyType[KeyType], Options>}
: {[KeyType in keyof AnyType]: AnyType[KeyType]};
/**
Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
@example
```
import type {Simplify} from 'type-fest';
type PositionProps = {
top: number;
left: number;
};
type SizeProps = {
width: number;
height: number;
};
// In your editor, hovering over `Props` will show a flattened object with all the properties.
type Props = Simplify<PositionProps & SizeProps>;
```
Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface.
If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`.
@example
```
import type {Simplify} from 'type-fest';
interface SomeInterface {
foo: number;
bar?: string;
baz: number | undefined;
}
type SomeType = {
foo: number;
bar?: string;
baz: number | undefined;
};
const literal = {foo: 123, bar: 'hello', baz: 456};
const someType: SomeType = literal;
const someInterface: SomeInterface = literal;
function fn(object: Record<string, unknown>): void {}
fn(literal); // Good: literal object type is sealed
fn(someType); // Good: type is sealed
fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
```
@link https://github.com/microsoft/TypeScript/issues/15300
@category Object
*/
export type Simplify<
AnyType,
Options extends SimplifyOptions = {},
> = Flatten<AnyType> extends AnyType
? Flatten<AnyType, Options>
: AnyType;

38
node_modules/type-fest/source/snake-case.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
import type {DelimiterCase} from './delimiter-case';
/**
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<T> = {
[K in keyof T as SnakeCase<K>]: T[K]
};
interface ModelProps {
isHappy: boolean;
fullFamilyName: string;
foo: number;
}
const dbResult: SnakeCasedProperties<ModelProps> = {
'is_happy': true,
'full_family_name': 'Carla Smith',
foo: 123
};
```
@category Change case
@category Template literal
*/
export type SnakeCase<Value> = DelimiterCase<Value, '_'>;

View File

@@ -0,0 +1,47 @@
import type {DelimiterCasedPropertiesDeep} from './delimiter-cased-properties-deep';
/**
Convert object properties to snake case recursively.
This can be useful when, for example, converting some API types from a different style.
@see SnakeCase
@see SnakeCasedProperties
@example
```
import type {SnakeCasedPropertiesDeep} from 'type-fest';
interface User {
userId: number;
userName: string;
}
interface UserWithFriends {
userInfo: User;
userFriends: User[];
}
const result: SnakeCasedPropertiesDeep<UserWithFriends> = {
user_info: {
user_id: 1,
user_name: 'Tom',
},
user_friends: [
{
user_id: 2,
user_name: 'Jerry',
},
{
user_id: 3,
user_name: 'Spike',
},
],
};
```
@category Change case
@category Template literal
@category Object
*/
export type SnakeCasedPropertiesDeep<Value> = DelimiterCasedPropertiesDeep<Value, '_'>;

View File

@@ -0,0 +1,30 @@
import type {DelimiterCasedProperties} from './delimiter-cased-properties';
/**
Convert object properties to snake case but not recursively.
This can be useful when, for example, converting some API types from a different style.
@see SnakeCase
@see SnakeCasedPropertiesDeep
@example
```
import type {SnakeCasedProperties} from 'type-fest';
interface User {
userId: number;
userName: string;
}
const result: SnakeCasedProperties<User> = {
user_id: 1,
user_name: 'Tom',
};
```
@category Change case
@category Template literal
@category Object
*/
export type SnakeCasedProperties<Value> = DelimiterCasedProperties<Value, '_'>;

29
node_modules/type-fest/source/split.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
Represents an array of strings split using a given character or character set.
Use-case: Defining the return type of a method like `String.prototype.split`.
@example
```
import type {Split} from 'type-fest';
declare function split<S extends string, D extends string>(string: S, separator: D): Split<S, D>;
type Item = 'foo' | 'bar' | 'baz' | 'waldo';
const items = 'foo,bar,baz,waldo';
let array: Item[];
array = split(items, ',');
```
@category String
@category Template literal
*/
export type Split<
S extends string,
Delimiter extends string,
> = S extends `${infer Head}${Delimiter}${infer Tail}`
? [Head, ...Split<Tail, Delimiter>]
: S extends Delimiter
? []
: [S];

85
node_modules/type-fest/source/spread.d.ts generated vendored Normal file
View File

@@ -0,0 +1,85 @@
import type {Except} from './except';
import type {RequiredKeysOf} from './required-keys-of';
import type {Simplify} from './simplify';
type SpreadObject<FirstType extends object, SecondType extends object> = {
[Key in keyof FirstType]: Key extends keyof SecondType
? FirstType[Key] | Required<SecondType>[Key]
: FirstType[Key];
} & Pick<
SecondType,
RequiredKeysOf<SecondType> | Exclude<keyof SecondType, keyof FirstType>
>;
type TupleOrArray = readonly [...unknown[]];
type SpreadTupleOrArray<
FirstType extends TupleOrArray,
SecondType extends TupleOrArray,
> = Array<FirstType[number] | SecondType[number]>;
type Spreadable = object | TupleOrArray;
/**
Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.
@example
```
import type {Spread} from 'type-fest';
type Foo = {
a: number;
b?: string;
};
type Bar = {
b?: number;
c: boolean;
};
const foo = {a: 1, b: '2'};
const bar = {c: false};
const fooBar = {...foo, ...bar};
type FooBar = Spread<Foo, Bar>;
// type FooBar = {
// a: number;
// b?: string | number | undefined;
// c: boolean;
// }
const baz = (argument: FooBar) => {
// Do something
}
baz(fooBar);
```
@example
```
import type {Spread} from 'type-fest';
const foo = [1, 2, 3];
const bar = ['4', '5', '6'];
const fooBar = [...foo, ...bar];
type FooBar = Spread<typeof foo, typeof bar>;
// FooBar = (string | number)[]
const baz = (argument: FooBar) => {
// Do something
};
baz(fooBar);
```
@category Object
*/
export type Spread<
FirstType extends Spreadable,
SecondType extends Spreadable,
> = FirstType extends TupleOrArray
? SecondType extends TupleOrArray
? SpreadTupleOrArray<FirstType, SecondType>
: Simplify<SpreadObject<FirstType, SecondType>>
: Simplify<SpreadObject<FirstType, SecondType>>;

25
node_modules/type-fest/source/string-key-of.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/**
Get keys of the given type as strings.
Number keys are converted to strings.
Use-cases:
- Get string keys from a type which may have number keys.
- Makes it possible to index using strings retrieved from template types.
@example
```
import type {StringKeyOf} from 'type-fest';
type Foo = {
1: number,
stringKey: string,
};
type StringKeysOfFoo = StringKeyOf<Foo>;
//=> '1' | 'stringKey'
```
@category Object
*/
export type StringKeyOf<BaseType> = `${Extract<keyof BaseType, string | number>}`;

23
node_modules/type-fest/source/stringified.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
/**
Create a type with the keys of the given type changed to `string` type.
Use-case: Changing interface values to strings in order to use them in a form model.
@example
```
import type {Stringified} from 'type-fest';
type Car {
model: string;
speed: number;
}
const carForm: Stringified<Car> = {
model: 'Foo',
speed: '101'
};
```
@category Object
*/
export type Stringified<ObjectType> = {[KeyType in keyof ObjectType]: string};

25
node_modules/type-fest/source/trim.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
/**
Remove spaces from the left side.
*/
type TrimLeft<V extends string> = V extends ` ${infer R}` ? TrimLeft<R> : V;
/**
Remove spaces from the right side.
*/
type TrimRight<V extends string> = V extends `${infer R} ` ? TrimRight<R> : V;
/**
Remove leading and trailing spaces from a string.
@example
```
import type {Trim} from 'type-fest';
Trim<' foo '>
//=> 'foo'
```
@category String
@category Template literal
*/
export type Trim<V extends string> = TrimLeft<TrimRight<V>>;

1172
node_modules/type-fest/source/tsconfig-json.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

17
node_modules/type-fest/source/typed-array.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
/**
Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
@category Array
*/
export type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array;

View File

@@ -0,0 +1,60 @@
/**
Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
@example
```
import type {UnionToIntersection} from 'type-fest';
type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
type Intersection = UnionToIntersection<Union>;
//=> {the(): void; great(arg: string): void; escape: boolean};
```
A more applicable example which could make its way into your library code follows.
@example
```
import type {UnionToIntersection} from 'type-fest';
class CommandOne {
commands: {
a1: () => undefined,
b1: () => undefined,
}
}
class CommandTwo {
commands: {
a2: (argA: string) => undefined,
b2: (argB: string) => undefined,
}
}
const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands);
type Union = typeof union;
//=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void}
type Intersection = UnionToIntersection<Union>;
//=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void}
```
@category Type
*/
export type UnionToIntersection<Union> = (
// `extends unknown` is always going to be the case and is used to convert the
// `Union` into a [distributive conditional
// type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
Union extends unknown
// The union type is used as the only argument to a function since the union
// of function arguments is an intersection.
? (distributedUnion: Union) => void
// This won't happen.
: never
// Infer the `Intersection` type since TypeScript represents the positional
// arguments of unions of functions as an intersection of the union.
) extends ((mergedIntersection: infer Intersection) => void)
? Intersection
: never;

42
node_modules/type-fest/source/value-of.d.ts generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/**
Create a union of the given object's values, and optionally specify which keys to get the values from.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript.
@example
```
// data.json
{
'foo': 1,
'bar': 2,
'biz': 3
}
// main.ts
import type {ValueOf} from 'type-fest';
import data = require('./data.json');
export function getData(name: string): ValueOf<typeof data> {
return data[name];
}
export function onlyBar(name: string): ValueOf<typeof data, 'bar'> {
return data[name];
}
// file.ts
import {getData, onlyBar} from './main';
getData('foo');
//=> 1
onlyBar('foo');
//=> TypeError ...
onlyBar('bar');
//=> 2
```
@category Object
*/
export type ValueOf<ObjectType, ValueType extends keyof ObjectType = keyof ObjectType> = ObjectType[ValueType];

40
node_modules/type-fest/source/writable.d.ts generated vendored Normal file
View File

@@ -0,0 +1,40 @@
import type {Except} from './except';
import type {Simplify} from './simplify';
/**
Create a type that strips `readonly` from all or some of an object's keys. Inverse of `Readonly<T>`.
This can be used to [store and mutate options within a class](https://github.com/sindresorhus/pageres/blob/4a5d05fca19a5fbd2f53842cbf3eb7b1b63bddd2/source/index.ts#L72), [edit `readonly` objects within tests](https://stackoverflow.com/questions/50703834), [construct a `readonly` object within a function](https://github.com/Microsoft/TypeScript/issues/24509), or to define a single model where the only thing that changes is whether or not some of the keys are writable.
@example
```
import type {Writable} from 'type-fest';
type Foo = {
readonly a: number;
readonly b: readonly string[]; // To show that only the mutability status of the properties, not their values, are affected.
readonly c: boolean;
};
const writableFoo: Writable<Foo> = {a: 1, b: ['2'], c: true};
writableFoo.a = 3;
writableFoo.b[0] = 'new value'; // Will still fail as the value of property "b" is still a readonly type.
writableFoo.b = ['something']; // Will work as the "b" property itself is no longer readonly.
type SomeWritable = Writable<Foo, 'b' | 'c'>;
// type SomeWritable = {
// readonly a: number;
// b: readonly string[]; // It's now writable. The type of the property remains unaffected.
// c: boolean; // It's now writable.
// }
```
@category Object
*/
export type Writable<BaseType, Keys extends keyof BaseType = keyof BaseType> =
Simplify<
// Pick just the keys that are not writable from the base type.
Except<BaseType, Keys> &
// Pick the keys that should be writable from the base type and make them writable by removing the `readonly` modifier from the key.
{-readonly [KeyType in keyof Pick<BaseType, Keys>]: Pick<BaseType, Keys>[KeyType]}
>;