From d5c9c2c2930109dd8a2ab0a4120477e701f8977d Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Wed, 29 Mar 2023 22:15:11 +0000 Subject: [PATCH 01/11] feat: add LiteralToPrimitiveDeep --- index.d.ts | 1 + readme.md | 1038 +++++++++++++------------ source/literal-to-primitive-deep.d.ts | 33 + test-d/literal-to-primitive-deep.ts | 49 ++ 4 files changed, 616 insertions(+), 505 deletions(-) create mode 100644 source/literal-to-primitive-deep.d.ts create mode 100644 test-d/literal-to-primitive-deep.ts diff --git a/index.d.ts b/index.d.ts index e1cc79d8d..83204bda4 100644 --- a/index.d.ts +++ b/index.d.ts @@ -55,6 +55,7 @@ export type {Jsonify} from './source/jsonify'; export type {Jsonifiable} from './source/jsonifiable'; export type {Schema} from './source/schema'; export type {LiteralToPrimitive} from './source/literal-to-primitive'; +export type {LiteralToPrimitiveDeep} from './source/literal-to-primitive-deep'; export type { PositiveInfinity, NegativeInfinity, diff --git a/readme.md b/readme.md index cbbf828f2..b22d0a3eb 100644 --- a/readme.md +++ b/readme.md @@ -95,19 +95,19 @@ PR welcome for additional commonly needed types and docs improvements. Read the npm install type-fest ``` -*Requires TypeScript >=4.7* +_Requires TypeScript >=4.7_ ## Usage ```ts -import type {Except} from 'type-fest'; +import type { Except } from "type-fest"; type Foo = { unicorn: string; rainbow: boolean; }; -type FooWithoutRainbow = Except; +type FooWithoutRainbow = Except; //=> {unicorn: string} ``` @@ -157,6 +157,7 @@ Click the type names for complete docs. - [`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. +- [`LiteralToPrimitiveDeep`](source/literal-to-primitive-deep.d.ts) - Like `LiteralToPrimitive` except that it converts the literal types deeply. - [`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. @@ -252,7 +253,7 @@ Click the type names for complete docs. ## Declined types -*If we decline a type addition, we will make sure to document the better solution here.* +_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` vs `Record`) 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. @@ -261,11 +262,11 @@ Click the type names for complete docs. - [`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. +- [`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.* +_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) @@ -277,20 +278,21 @@ Click the type names for complete docs. ### 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. -
- - Example - +
+ + Example + - [Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBDAnmApnA3gBQIYGMDW2A5igFIDOEAdnNuXAEJ0o4HFmVUC+cAZlBBBwA5ElQBaXinIxhAbgCwAKFCRYCZGnQAZYFRgooPfoJHSANntmKlysWlaESFanAC8jZo-YuaAMgwLKwBhal5gIgB+AC44XX1DADpQqnCiLhsgA) + [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'; + ```ts + import type { PackageJson as BasePackageJson } from "type-fest"; + import type { Linter } from "eslint"; - type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config}; - ``` -
+ type PackageJson = BasePackageJson & { eslintConfig?: Linter.Config }; + ``` + +
### Related @@ -302,602 +304,628 @@ Click the type names for complete docs. There are many advanced types most users don't know about. - [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) - Make all properties in `T` optional. -
- - Example - +
+ + Example + + + [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA) - [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA) + ```ts + interface NodeConfig { + appName: string; + port: number; + } - ```ts - interface NodeConfig { - appName: string; - port: number; - } + class NodeAppBuilder { + private configuration: NodeConfig = { + appName: "NodeApp", + port: 3000, + }; - class NodeAppBuilder { - private configuration: NodeConfig = { - appName: 'NodeApp', - port: 3000 - }; + private updateConfig( + key: Key, + value: NodeConfig[Key] + ) { + this.configuration[key] = value; + } - private updateConfig(key: Key, value: NodeConfig[Key]) { - this.configuration[key] = value; - } + config(config: Partial) { + type NodeConfigKey = keyof NodeConfig; - config(config: Partial) { - type NodeConfigKey = keyof NodeConfig; + for (const key of Object.keys(config) as NodeConfigKey[]) { + const updateValue = config[key]; - for (const key of Object.keys(config) as NodeConfigKey[]) { - const updateValue = config[key]; + if (updateValue === undefined) { + continue; + } - if (updateValue === undefined) { - continue; - } + this.updateConfig(key, updateValue); + } - this.updateConfig(key, updateValue); - } + return this; + } + } - return this; - } - } + // `Partial`` allows us to provide only a part of the + // NodeConfig interface. + new NodeAppBuilder().config({ appName: "ToDoApp" }); + ``` - // `Partial`` allows us to provide only a part of the - // NodeConfig interface. - new NodeAppBuilder().config({appName: 'ToDoApp'}); - ``` -
+
- [`Required`](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype) - Make all properties in `T` required. -
- - Example - - - [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) { - // 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', - }); - ``` -
+
+ + Example + + + [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) { + // 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", + }); + ``` + +
- [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) - Make all properties in `T` readonly. -
- - Example - - - [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; - - 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; - ``` -
+
+ + Example + + + [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; + + 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; + ``` + +
- [`Pick`](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`. -
- - Example - - - [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; - - // 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' - } - ]); - ``` -
+
+ + Example + + + [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; + + // 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", + }, + ]); + ``` + +
- [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) - Construct a type with a set of properties `K` of type `T`. -
- - Example - - - [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 = { - 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 = { - intern: null, - developer: null, - }; - ``` -
+
+ + Example + + + [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 = { + 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 = { + intern: null, + developer: null, + }; + ``` + +
- [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion) - Exclude from `T` those types that are assignable to `U`. -
- - Example - +
+ + Example + - [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA) + [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA) - ```ts - interface ServerConfig { - port: null | string | number; - } + ```ts + interface ServerConfig { + port: null | string | number; + } - type RequestHandler = (request: Request, response: Response) => void; + 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): number { - if (typeof port === 'string') { - return parseInt(port, 10); - } + // Exclude `null` type from `null | string | number`. + // In case the port is equal to `null`, we will use default value. + function getPortValue(port: Exclude): number { + if (typeof port === "string") { + return parseInt(port, 10); + } - return port; - } + return port; + } - function startServer(handler: RequestHandler, config: ServerConfig): void { - const server = require('http').createServer(handler); + 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); - } - ``` -
+ const port = config.port === null ? 3000 : getPortValue(config.port); + server.listen(port); + } + ``` + +
- [`Extract`](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union) - Extract from `T` those types that are assignable to `U`. -
- - Example - - - [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, - 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()); - ``` -
+
+ + Example + + + [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, + 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()); + ``` + +
- [`NonNullable`](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype) - Exclude `null` and `undefined` from `T`. -
- - Example - - Works with strictNullChecks set to true. +
+ + Example + + Works with strictNullChecks set to true. + + [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA) - [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA) + ```ts + type PortNumber = string | number | null; - ```ts - type PortNumber = string | number | null; + /** Part of a class definition that is used to build a server */ + class ServerBuilder { + portNumber!: NonNullable; - /** Part of a class definition that is used to build a server */ - class ServerBuilder { - portNumber!: NonNullable; + port(this: ServerBuilder, port: PortNumber): ServerBuilder { + if (port == null) { + this.portNumber = 8000; + } else { + this.portNumber = port; + } - port(this: ServerBuilder, port: PortNumber): ServerBuilder { - if (port == null) { - this.portNumber = 8000; - } else { - this.portNumber = port; - } + return this; + } + } - return this; - } - } + const serverBuilder = new ServerBuilder(); - const serverBuilder = new ServerBuilder(); + serverBuilder + .port("8000") // portNumber = '8000' + .port(null) // portNumber = 8000 + .port(3000); // portNumber = 3000 - serverBuilder - .port('8000') // portNumber = '8000' - .port(null) // portNumber = 8000 - .port(3000); // portNumber = 3000 + // TypeScript error + serverBuilder.portNumber = null; + ``` - // TypeScript error - serverBuilder.portNumber = null; - ``` -
+
- [`Parameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype) - Obtain the parameters of a function type in a tuple. -
- - Example - +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA) - [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. + } - ```ts - function shuffle(input: any[]): void { - // Mutate array randomly changing its' elements indexes. - } + function callNTimes any>( + func: Fn, + callCount: number + ) { + // Type that represents the type of the received function parameters. + type FunctionParameters = Parameters; - function callNTimes any> (func: Fn, callCount: number) { - // Type that represents the type of the received function parameters. - type FunctionParameters = Parameters; + return function (...arguments_: FunctionParameters) { + for (let i = 0; i < callCount; i++) { + func(...arguments_); + } + }; + } - return function (...arguments_: FunctionParameters) { - for (let i = 0; i < callCount; i++) { - func(...arguments_); - } - } - } + const shuffleTwice = callNTimes(shuffle, 2); + ``` - const shuffleTwice = callNTimes(shuffle, 2); - ``` -
+
- [`ConstructorParameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#constructorparameterstype) - Obtain the parameters of a constructor function type in a tuple. -
- - Example - +
+ + Example + - [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA) + [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; + ```ts + class ArticleModel { + title: string; + content?: string; - constructor(title: string) { - this.title = title; - } - } + constructor(title: string) { + this.title = title; + } + } - class InstanceCache any)> { - private ClassConstructor: T; - private cache: Map> = new Map(); + class InstanceCache any> { + private ClassConstructor: T; + private cache: Map> = new Map(); - constructor (ctr: T) { - this.ClassConstructor = ctr; - } + constructor(ctr: T) { + this.ClassConstructor = ctr; + } - getInstance (...arguments_: ConstructorParameters): InstanceType { - const hash = this.calculateArgumentsHash(...arguments_); + getInstance(...arguments_: ConstructorParameters): InstanceType { + const hash = this.calculateArgumentsHash(...arguments_); - const existingInstance = this.cache.get(hash); - if (existingInstance !== undefined) { - return existingInstance; - } + const existingInstance = this.cache.get(hash); + if (existingInstance !== undefined) { + return existingInstance; + } - return new this.ClassConstructor(...arguments_); - } + return new this.ClassConstructor(...arguments_); + } - private calculateArgumentsHash(...arguments_: any[]): string { - // Calculate hash. - return 'hash'; - } - } + private calculateArgumentsHash(...arguments_: any[]): string { + // Calculate hash. + return "hash"; + } + } - const articleCache = new InstanceCache(ArticleModel); - const amazonArticle = articleCache.getInstance('Amazon forests burining!'); - ``` -
+ const articleCache = new InstanceCache(ArticleModel); + const amazonArticle = articleCache.getInstance("Amazon forests burining!"); + ``` + +
- [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype) - Obtain the return type of a function type. -
- - Example - +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) - [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 + >(iter: Iterable, callback: Func): Ret[] { + const mapped: Ret[] = []; - ```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 - >(iter: Iterable, callback: Func): Ret[] { - const mapped: Ret[] = []; + for (const elem of iter) { + mapped.push(callback(elem)); + } - for (const elem of iter) { - mapped.push(callback(elem)); - } + return mapped; + } - return mapped; - } + const setObject: Set = new Set(); + const mapObject: Map = new Map(); - const setObject: Set = new Set(); - const mapObject: Map = new Map(); + mapIter(setObject, (value: string) => value.indexOf("Foo")); // number[] - mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[] + mapIter(mapObject, ([key, value]: [number, string]) => { + return key % 2 === 0 ? value : "Odd"; + }); // string[] + ``` - mapIter(mapObject, ([key, value]: [number, string]) => { - return key % 2 === 0 ? value : 'Odd'; - }); // string[] - ``` -
+
- [`InstanceType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype) - Obtain the instance type of a constructor function type. -
- - Example - +
+ + Example + - [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) - ```ts - class IdleService { - doNothing (): void {} - } + ```ts + class IdleService { + doNothing(): void {} + } - class News { - title: string; - content: string; + class News { + title: string; + content: string; - constructor(title: string, content: string) { - this.title = title; - this.content = content; - } - } + constructor(title: string, content: string) { + this.title = title; + this.content = content; + } + } - const instanceCounter: Map = new Map(); + const instanceCounter: Map = new Map(); - interface Constructor { - new(...arguments_: any[]): any; - } + interface Constructor { + new (...arguments_: any[]): any; + } - // Keep track how many instances of `Constr` constructor have been created. - function getInstance< - Constr extends Constructor, - Arguments extends ConstructorParameters - >(constructor: Constr, ...arguments_: Arguments): InstanceType { - let count = instanceCounter.get(constructor) || 0; + // Keep track how many instances of `Constr` constructor have been created. + function getInstance< + Constr extends Constructor, + Arguments extends ConstructorParameters + >(constructor: Constr, ...arguments_: Arguments): InstanceType { + let count = instanceCounter.get(constructor) || 0; - const instance = new constructor(...arguments_); + const instance = new constructor(...arguments_); - instanceCounter.set(constructor, count + 1); + instanceCounter.set(constructor, count + 1); - console.log(`Created ${count + 1} instances of ${Constr.name} class`); + console.log(`Created ${count + 1} instances of ${Constr.name} class`); - return instance; - } + 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` + ``` - 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` - ``` -
+
- [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) - Constructs a type by picking all properties from T and then removing K. -
- - Example - - - [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; - - function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement { - const container = document.createElement('div'); - // Internal implementation. - return container; - } - ``` -
+
+ + Example + + + [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; + + function renderAnimalHoverInfo(animals: AnimalShortInfo[]): HTMLElement { + const container = document.createElement("div"); + // Internal implementation. + return container; + } + ``` + +
- [`Uppercase`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype) - Transforms every character in a string into uppercase. -
- - Example - +
+ + Example + - ```ts - type T = Uppercase<'hello'>; // 'HELLO' + ```ts + type T = Uppercase<"hello">; // 'HELLO' - type T2 = Uppercase<'foo' | 'bar'>; // 'FOO' | 'BAR' + type T2 = Uppercase<"foo" | "bar">; // 'FOO' | 'BAR' - type T3 = Uppercase<`aB${S}`>; - type T4 = T3<'xYz'>; // 'ABXYZ' + type T3 = Uppercase<`aB${S}`>; + type T4 = T3<"xYz">; // 'ABXYZ' - type T5 = Uppercase; // string - type T6 = Uppercase; // any - type T7 = Uppercase; // never - type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` -
+ type T5 = Uppercase; // string + type T6 = Uppercase; // any + type T7 = Uppercase; // never + type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` + +
- [`Lowercase`](https://www.typescriptlang.org/docs/handbook/utility-types.html#lowercasestringtype) - Transforms every character in a string into lowercase. -
- - Example - +
+ + Example + + + ```ts + type T = Lowercase<"HELLO">; // 'hello' - ```ts - type T = Lowercase<'HELLO'>; // 'hello' + type T2 = Lowercase<"FOO" | "BAR">; // 'foo' | 'bar' - type T2 = Lowercase<'FOO' | 'BAR'>; // 'foo' | 'bar' + type T3 = Lowercase<`aB${S}`>; + type T4 = T3<"xYz">; // 'abxyz' - type T3 = Lowercase<`aB${S}`>; - type T4 = T3<'xYz'>; // 'abxyz' + type T5 = Lowercase; // string + type T6 = Lowercase; // any + type T7 = Lowercase; // never + type T8 = Lowercase<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` - type T5 = Lowercase; // string - type T6 = Lowercase; // any - type T7 = Lowercase; // never - type T8 = Lowercase<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` -
+
- [`Capitalize`](https://www.typescriptlang.org/docs/handbook/utility-types.html#capitalizestringtype) - Transforms the first character in a string into uppercase. -
- - Example - +
+ + Example + - ```ts - type T = Capitalize<'hello'>; // 'Hello' + ```ts + type T = Capitalize<"hello">; // 'Hello' - type T2 = Capitalize<'foo' | 'bar'>; // 'Foo' | 'Bar' + type T2 = Capitalize<"foo" | "bar">; // 'Foo' | 'Bar' - type T3 = Capitalize<`aB${S}`>; - type T4 = T3<'xYz'>; // 'ABxYz' + type T3 = Capitalize<`aB${S}`>; + type T4 = T3<"xYz">; // 'ABxYz' - type T5 = Capitalize; // string - type T6 = Capitalize; // any - type T7 = Capitalize; // never - type T8 = Capitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` -
+ type T5 = Capitalize; // string + type T6 = Capitalize; // any + type T7 = Capitalize; // never + type T8 = Capitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` + +
- [`Uncapitalize`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uncapitalizestringtype) - Transforms the first character in a string into lowercase. -
- - Example - +
+ + Example + + + ```ts + type T = Uncapitalize<"Hello">; // 'hello' - ```ts - type T = Uncapitalize<'Hello'>; // 'hello' + type T2 = Uncapitalize<"Foo" | "Bar">; // 'foo' | 'bar' - type T2 = Uncapitalize<'Foo' | 'Bar'>; // 'foo' | 'bar' + type T3 = Uncapitalize<`AB${S}`>; + type T4 = T3<"xYz">; // 'aBxYz' - type T3 = Uncapitalize<`AB${S}`>; - type T4 = T3<'xYz'>; // 'aBxYz' + type T5 = Uncapitalize; // string + type T6 = Uncapitalize; // any + type T7 = Uncapitalize; // never + type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` - type T5 = Uncapitalize; // string - type T6 = Uncapitalize; // any - type T7 = Uncapitalize; // never - type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` -
+
You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/utility-types.html). diff --git a/source/literal-to-primitive-deep.d.ts b/source/literal-to-primitive-deep.d.ts new file mode 100644 index 000000000..7f919e7b8 --- /dev/null +++ b/source/literal-to-primitive-deep.d.ts @@ -0,0 +1,33 @@ +import type {LiteralToPrimitive} from './literal-to-primitive'; +import type {OmitIndexSignature} from './omit-index-signature'; + +/** + * Given a constant object, return a new object with the same keys but with all the values converted to primitives. + * @see LiteralToPrimitive + * + * Use-case: Deal with data that is imported from a JSON file. + * + * @example + * ``` + * import type { LiteralToPrimitiveDeep, TsConfigJson } from 'type-fest'; + * import tsconfig from 'path/to/tsconfig.json'; + * + * function doSomethingWithTSConfig(config: LiteralToPrimitiveDeep) { ... } + * + * // no casting is needed to pass the type check + * doSomethingWithTSConfig(tsconfig); + * + * // if LiteralToPrimitiveDeep is not used, you need to cast the imported data like this: + * doSomethingWithTSConfig(tsconfig as TsConfigJson); + * ``` + * + * @category Type + * @category Object + */ +export type LiteralToPrimitiveDeep = T extends object + ? T extends Array + ? Array> + : { + [K in keyof OmitIndexSignature]: LiteralToPrimitiveDeep; + } + : LiteralToPrimitive; diff --git a/test-d/literal-to-primitive-deep.ts b/test-d/literal-to-primitive-deep.ts new file mode 100644 index 000000000..f79e94600 --- /dev/null +++ b/test-d/literal-to-primitive-deep.ts @@ -0,0 +1,49 @@ +import {expectType} from 'tsd'; +import type {LiteralToPrimitiveDeep} from '../index'; + +declare const subject: { + a: string; + b: number; + c: boolean; + d: { + e: bigint; + f: symbol; + g: { + h: string[]; + i: { + j: boolean; + k: { + l: 1; + m: 'hello'; + o: [1, 2, 3]; + p: ['a', 'b', 'c']; + q: [1, 'a', true]; + }; + }; + }; + }; +}; + +type Expected = { + a: string; + b: number; + c: boolean; + d: { + e: bigint; + f: symbol; + g: { + h: string[]; + i: { + j: boolean; + k: { + l: number; + m: string; + o: number[]; + p: string[]; + q: Array; + }; + }; + }; + }; +}; +expectType(subject); From 957777bbeb411a272970345fc8f94a2dcc8467d8 Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Wed, 29 Mar 2023 22:51:30 +0000 Subject: [PATCH 02/11] fix: correct the test --- test-d/literal-to-primitive-deep.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/test-d/literal-to-primitive-deep.ts b/test-d/literal-to-primitive-deep.ts index f79e94600..735897e97 100644 --- a/test-d/literal-to-primitive-deep.ts +++ b/test-d/literal-to-primitive-deep.ts @@ -1,7 +1,7 @@ import {expectType} from 'tsd'; -import type {LiteralToPrimitiveDeep} from '../index'; +import type {IsEqual, LiteralToPrimitiveDeep} from '../index'; -declare const subject: { +type LiteralObject = { a: string; b: number; c: boolean; @@ -24,7 +24,7 @@ declare const subject: { }; }; -type Expected = { +type PrimitiveObject = { a: string; b: number; c: boolean; @@ -46,4 +46,9 @@ type Expected = { }; }; }; -expectType(subject); + +const typeEqual: IsEqual< +LiteralToPrimitiveDeep, +PrimitiveObject +> = true; +expectType(typeEqual); From a3d2911aa014fd63782d37d81af31b2b653ee8bc Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Fri, 31 Mar 2023 12:29:45 +0000 Subject: [PATCH 03/11] doc: undo changes by auto formmater --- readme.md | 1039 ++++++++++++++++++++++++++--------------------------- 1 file changed, 506 insertions(+), 533 deletions(-) diff --git a/readme.md b/readme.md index b22d0a3eb..1b2ee25ce 100644 --- a/readme.md +++ b/readme.md @@ -95,19 +95,19 @@ PR welcome for additional commonly needed types and docs improvements. Read the npm install type-fest ``` -_Requires TypeScript >=4.7_ +*Requires TypeScript >=4.7* ## Usage ```ts -import type { Except } from "type-fest"; +import type {Except} from 'type-fest'; type Foo = { unicorn: string; rainbow: boolean; }; -type FooWithoutRainbow = Except; +type FooWithoutRainbow = Except; //=> {unicorn: string} ``` @@ -253,7 +253,7 @@ Click the type names for complete docs. ## Declined types -_If we decline a type addition, we will make sure to document the better solution here._ +*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` vs `Record`) 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. @@ -262,11 +262,11 @@ _If we decline a type addition, we will make sure to document the better solutio - [`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. +- [`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._ +*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) @@ -278,21 +278,20 @@ _If you know one of our types by a different name, add it here for discovery._ ### 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. -
- - Example - +
+ + Example + - [Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBDAnmApnA3gBQIYGMDW2A5igFIDOEAdnNuXAEJ0o4HFmVUC+cAZlBBBwA5ElQBaXinIxhAbgCwAKFCRYCZGnQAZYFRgooPfoJHSANntmKlysWlaESFanAC8jZo-YuaAMgwLKwBhal5gIgB+AC44XX1DADpQqnCiLhsgA) + [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"; + ```ts + import type {PackageJson as BasePackageJson} from 'type-fest'; + import type {Linter} from 'eslint'; - type PackageJson = BasePackageJson & { eslintConfig?: Linter.Config }; - ``` - -
+ type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config}; + ``` +
### Related @@ -304,628 +303,602 @@ _If you know one of our types by a different name, add it here for discovery._ There are many advanced types most users don't know about. - [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) - Make all properties in `T` optional. -
- - Example - - - [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA) +
+ + Example + - ```ts - interface NodeConfig { - appName: string; - port: number; - } + [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA) - class NodeAppBuilder { - private configuration: NodeConfig = { - appName: "NodeApp", - port: 3000, - }; + ```ts + interface NodeConfig { + appName: string; + port: number; + } - private updateConfig( - key: Key, - value: NodeConfig[Key] - ) { - this.configuration[key] = value; - } + class NodeAppBuilder { + private configuration: NodeConfig = { + appName: 'NodeApp', + port: 3000 + }; - config(config: Partial) { - type NodeConfigKey = keyof NodeConfig; + private updateConfig(key: Key, value: NodeConfig[Key]) { + this.configuration[key] = value; + } - for (const key of Object.keys(config) as NodeConfigKey[]) { - const updateValue = config[key]; + config(config: Partial) { + type NodeConfigKey = keyof NodeConfig; - if (updateValue === undefined) { - continue; - } + for (const key of Object.keys(config) as NodeConfigKey[]) { + const updateValue = config[key]; - this.updateConfig(key, updateValue); - } + if (updateValue === undefined) { + continue; + } - return this; - } - } + this.updateConfig(key, updateValue); + } - // `Partial`` allows us to provide only a part of the - // NodeConfig interface. - new NodeAppBuilder().config({ appName: "ToDoApp" }); - ``` + return this; + } + } -
+ // `Partial`` allows us to provide only a part of the + // NodeConfig interface. + new NodeAppBuilder().config({appName: 'ToDoApp'}); + ``` +
- [`Required`](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype) - Make all properties in `T` required. -
- - Example - - - [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) { - // 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", - }); - ``` - -
+
+ + Example + + + [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) { + // 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', + }); + ``` +
- [`Readonly`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) - Make all properties in `T` readonly. -
- - Example - - - [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; - - 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; - ``` - -
+
+ + Example + + + [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; + + 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; + ``` +
- [`Pick`](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`. -
- - Example - - - [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; - - // 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", - }, - ]); - ``` - -
+
+ + Example + + + [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; + + // 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' + } + ]); + ``` +
- [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) - Construct a type with a set of properties `K` of type `T`. -
- - Example - - - [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 = { - 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 = { - intern: null, - developer: null, - }; - ``` - -
+
+ + Example + + + [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 = { + 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 = { + intern: null, + developer: null, + }; + ``` +
- [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion) - Exclude from `T` those types that are assignable to `U`. -
- - Example - +
+ + Example + - [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA) + [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA) - ```ts - interface ServerConfig { - port: null | string | number; - } + ```ts + interface ServerConfig { + port: null | string | number; + } - type RequestHandler = (request: Request, response: Response) => void; + 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): number { - if (typeof port === "string") { - return parseInt(port, 10); - } + // Exclude `null` type from `null | string | number`. + // In case the port is equal to `null`, we will use default value. + function getPortValue(port: Exclude): number { + if (typeof port === 'string') { + return parseInt(port, 10); + } - return port; - } + return port; + } - function startServer(handler: RequestHandler, config: ServerConfig): void { - const server = require("http").createServer(handler); + 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); - } - ``` - -
+ const port = config.port === null ? 3000 : getPortValue(config.port); + server.listen(port); + } + ``` +
- [`Extract`](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union) - Extract from `T` those types that are assignable to `U`. -
- - Example - - - [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, - 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()); - ``` - -
+
+ + Example + + + [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, + 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()); + ``` +
- [`NonNullable`](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype) - Exclude `null` and `undefined` from `T`. -
- - Example - - Works with strictNullChecks set to true. - - [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA) +
+ + Example + + Works with strictNullChecks set to true. - ```ts - type PortNumber = string | number | null; + [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA) - /** Part of a class definition that is used to build a server */ - class ServerBuilder { - portNumber!: NonNullable; + ```ts + type PortNumber = string | number | null; - port(this: ServerBuilder, port: PortNumber): ServerBuilder { - if (port == null) { - this.portNumber = 8000; - } else { - this.portNumber = port; - } + /** Part of a class definition that is used to build a server */ + class ServerBuilder { + portNumber!: NonNullable; - return this; - } - } + port(this: ServerBuilder, port: PortNumber): ServerBuilder { + if (port == null) { + this.portNumber = 8000; + } else { + this.portNumber = port; + } - const serverBuilder = new ServerBuilder(); + return this; + } + } - serverBuilder - .port("8000") // portNumber = '8000' - .port(null) // portNumber = 8000 - .port(3000); // portNumber = 3000 + const serverBuilder = new ServerBuilder(); - // TypeScript error - serverBuilder.portNumber = null; - ``` + serverBuilder + .port('8000') // portNumber = '8000' + .port(null) // portNumber = 8000 + .port(3000); // portNumber = 3000 -
+ // TypeScript error + serverBuilder.portNumber = null; + ``` +
- [`Parameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype) - Obtain the parameters of a function type in a tuple. -
- - Example - - - [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA) +
+ + Example + - ```ts - function shuffle(input: any[]): void { - // Mutate array randomly changing its' elements indexes. - } + [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA) - function callNTimes any>( - func: Fn, - callCount: number - ) { - // Type that represents the type of the received function parameters. - type FunctionParameters = Parameters; + ```ts + function shuffle(input: any[]): void { + // Mutate array randomly changing its' elements indexes. + } - return function (...arguments_: FunctionParameters) { - for (let i = 0; i < callCount; i++) { - func(...arguments_); - } - }; - } + function callNTimes any> (func: Fn, callCount: number) { + // Type that represents the type of the received function parameters. + type FunctionParameters = Parameters; - const shuffleTwice = callNTimes(shuffle, 2); - ``` + return function (...arguments_: FunctionParameters) { + for (let i = 0; i < callCount; i++) { + func(...arguments_); + } + } + } -
+ const shuffleTwice = callNTimes(shuffle, 2); + ``` +
- [`ConstructorParameters`](https://www.typescriptlang.org/docs/handbook/utility-types.html#constructorparameterstype) - Obtain the parameters of a constructor function type in a tuple. -
- - Example - +
+ + Example + - [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA) + [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; + ```ts + class ArticleModel { + title: string; + content?: string; - constructor(title: string) { - this.title = title; - } - } + constructor(title: string) { + this.title = title; + } + } - class InstanceCache any> { - private ClassConstructor: T; - private cache: Map> = new Map(); + class InstanceCache any)> { + private ClassConstructor: T; + private cache: Map> = new Map(); - constructor(ctr: T) { - this.ClassConstructor = ctr; - } + constructor (ctr: T) { + this.ClassConstructor = ctr; + } - getInstance(...arguments_: ConstructorParameters): InstanceType { - const hash = this.calculateArgumentsHash(...arguments_); + getInstance (...arguments_: ConstructorParameters): InstanceType { + const hash = this.calculateArgumentsHash(...arguments_); - const existingInstance = this.cache.get(hash); - if (existingInstance !== undefined) { - return existingInstance; - } + const existingInstance = this.cache.get(hash); + if (existingInstance !== undefined) { + return existingInstance; + } - return new this.ClassConstructor(...arguments_); - } + return new this.ClassConstructor(...arguments_); + } - private calculateArgumentsHash(...arguments_: any[]): string { - // Calculate hash. - return "hash"; - } - } + private calculateArgumentsHash(...arguments_: any[]): string { + // Calculate hash. + return 'hash'; + } + } - const articleCache = new InstanceCache(ArticleModel); - const amazonArticle = articleCache.getInstance("Amazon forests burining!"); - ``` - -
+ const articleCache = new InstanceCache(ArticleModel); + const amazonArticle = articleCache.getInstance('Amazon forests burining!'); + ``` +
- [`ReturnType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype) - Obtain the return type of a function type. -
- - Example - - - [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) +
+ + Example + - ```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 - >(iter: Iterable, callback: Func): Ret[] { - const mapped: Ret[] = []; + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) - for (const elem of iter) { - mapped.push(callback(elem)); - } + ```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 + >(iter: Iterable, callback: Func): Ret[] { + const mapped: Ret[] = []; - return mapped; - } + for (const elem of iter) { + mapped.push(callback(elem)); + } - const setObject: Set = new Set(); - const mapObject: Map = new Map(); + return mapped; + } - mapIter(setObject, (value: string) => value.indexOf("Foo")); // number[] + const setObject: Set = new Set(); + const mapObject: Map = new Map(); - mapIter(mapObject, ([key, value]: [number, string]) => { - return key % 2 === 0 ? value : "Odd"; - }); // string[] - ``` + mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[] -
+ mapIter(mapObject, ([key, value]: [number, string]) => { + return key % 2 === 0 ? value : 'Odd'; + }); // string[] + ``` +
- [`InstanceType`](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype) - Obtain the instance type of a constructor function type. -
- - Example - +
+ + Example + - [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) - ```ts - class IdleService { - doNothing(): void {} - } + ```ts + class IdleService { + doNothing (): void {} + } - class News { - title: string; - content: string; + class News { + title: string; + content: string; - constructor(title: string, content: string) { - this.title = title; - this.content = content; - } - } + constructor(title: string, content: string) { + this.title = title; + this.content = content; + } + } - const instanceCounter: Map = new Map(); + const instanceCounter: Map = new Map(); - interface Constructor { - new (...arguments_: any[]): any; - } + interface Constructor { + new(...arguments_: any[]): any; + } - // Keep track how many instances of `Constr` constructor have been created. - function getInstance< - Constr extends Constructor, - Arguments extends ConstructorParameters - >(constructor: Constr, ...arguments_: Arguments): InstanceType { - let count = instanceCounter.get(constructor) || 0; + // Keep track how many instances of `Constr` constructor have been created. + function getInstance< + Constr extends Constructor, + Arguments extends ConstructorParameters + >(constructor: Constr, ...arguments_: Arguments): InstanceType { + let count = instanceCounter.get(constructor) || 0; - const instance = new constructor(...arguments_); + const instance = new constructor(...arguments_); - instanceCounter.set(constructor, count + 1); + instanceCounter.set(constructor, count + 1); - console.log(`Created ${count + 1} instances of ${Constr.name} class`); + console.log(`Created ${count + 1} instances of ${Constr.name} class`); - return instance; - } + 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` - ``` -
+ 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` + ``` +
- [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) - Constructs a type by picking all properties from T and then removing K. -
- - Example - - - [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; - - function renderAnimalHoverInfo(animals: AnimalShortInfo[]): HTMLElement { - const container = document.createElement("div"); - // Internal implementation. - return container; - } - ``` - -
+
+ + Example + + + [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; + + function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement { + const container = document.createElement('div'); + // Internal implementation. + return container; + } + ``` +
- [`Uppercase`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype) - Transforms every character in a string into uppercase. -
- - Example - +
+ + Example + - ```ts - type T = Uppercase<"hello">; // 'HELLO' + ```ts + type T = Uppercase<'hello'>; // 'HELLO' - type T2 = Uppercase<"foo" | "bar">; // 'FOO' | 'BAR' + type T2 = Uppercase<'foo' | 'bar'>; // 'FOO' | 'BAR' - type T3 = Uppercase<`aB${S}`>; - type T4 = T3<"xYz">; // 'ABXYZ' + type T3 = Uppercase<`aB${S}`>; + type T4 = T3<'xYz'>; // 'ABXYZ' - type T5 = Uppercase; // string - type T6 = Uppercase; // any - type T7 = Uppercase; // never - type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` - -
+ type T5 = Uppercase; // string + type T6 = Uppercase; // any + type T7 = Uppercase; // never + type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
- [`Lowercase`](https://www.typescriptlang.org/docs/handbook/utility-types.html#lowercasestringtype) - Transforms every character in a string into lowercase. -
- - Example - - - ```ts - type T = Lowercase<"HELLO">; // 'hello' +
+ + Example + - type T2 = Lowercase<"FOO" | "BAR">; // 'foo' | 'bar' + ```ts + type T = Lowercase<'HELLO'>; // 'hello' - type T3 = Lowercase<`aB${S}`>; - type T4 = T3<"xYz">; // 'abxyz' + type T2 = Lowercase<'FOO' | 'BAR'>; // 'foo' | 'bar' - type T5 = Lowercase; // string - type T6 = Lowercase; // any - type T7 = Lowercase; // never - type T8 = Lowercase<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` + type T3 = Lowercase<`aB${S}`>; + type T4 = T3<'xYz'>; // 'abxyz' -
+ type T5 = Lowercase; // string + type T6 = Lowercase; // any + type T7 = Lowercase; // never + type T8 = Lowercase<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
- [`Capitalize`](https://www.typescriptlang.org/docs/handbook/utility-types.html#capitalizestringtype) - Transforms the first character in a string into uppercase. -
- - Example - +
+ + Example + - ```ts - type T = Capitalize<"hello">; // 'Hello' + ```ts + type T = Capitalize<'hello'>; // 'Hello' - type T2 = Capitalize<"foo" | "bar">; // 'Foo' | 'Bar' + type T2 = Capitalize<'foo' | 'bar'>; // 'Foo' | 'Bar' - type T3 = Capitalize<`aB${S}`>; - type T4 = T3<"xYz">; // 'ABxYz' + type T3 = Capitalize<`aB${S}`>; + type T4 = T3<'xYz'>; // 'ABxYz' - type T5 = Capitalize; // string - type T6 = Capitalize; // any - type T7 = Capitalize; // never - type T8 = Capitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` - -
+ type T5 = Capitalize; // string + type T6 = Capitalize; // any + type T7 = Capitalize; // never + type T8 = Capitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
- [`Uncapitalize`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uncapitalizestringtype) - Transforms the first character in a string into lowercase. -
- - Example - - - ```ts - type T = Uncapitalize<"Hello">; // 'hello' +
+ + Example + - type T2 = Uncapitalize<"Foo" | "Bar">; // 'foo' | 'bar' + ```ts + type T = Uncapitalize<'Hello'>; // 'hello' - type T3 = Uncapitalize<`AB${S}`>; - type T4 = T3<"xYz">; // 'aBxYz' + type T2 = Uncapitalize<'Foo' | 'Bar'>; // 'foo' | 'bar' - type T5 = Uncapitalize; // string - type T6 = Uncapitalize; // any - type T7 = Uncapitalize; // never - type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' - ``` + type T3 = Uncapitalize<`AB${S}`>; + type T4 = T3<'xYz'>; // 'aBxYz' -
+ type T5 = Uncapitalize; // string + type T6 = Uncapitalize; // any + type T7 = Uncapitalize; // never + type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/utility-types.html). @@ -939,4 +912,4 @@ You can find some examples in the [TypeScript docs](https://www.typescriptlang.o ## License -SPDX-License-Identifier: (MIT OR CC0-1.0) +SPDX-License-Identifier: (MIT OR CC0-1.0) \ No newline at end of file From dbacfc4336ae174fc761d590a80ca9affe9b1f83 Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Fri, 31 Mar 2023 12:31:16 +0000 Subject: [PATCH 04/11] doc: undo changes by auto formmater --- readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/readme.md b/readme.md index 1b2ee25ce..d70cfa9ca 100644 --- a/readme.md +++ b/readme.md @@ -911,5 +911,4 @@ You can find some examples in the [TypeScript docs](https://www.typescriptlang.o - [Sébastien Mischler](https://github.com/skarab42) ## License - SPDX-License-Identifier: (MIT OR CC0-1.0) \ No newline at end of file From 8f3c570e1afe33c6fe81bfc4c6684aa9e4a130d0 Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Fri, 31 Mar 2023 12:33:10 +0000 Subject: [PATCH 05/11] doc: undo changes made by auto formatter --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index d70cfa9ca..1b2ee25ce 100644 --- a/readme.md +++ b/readme.md @@ -911,4 +911,5 @@ You can find some examples in the [TypeScript docs](https://www.typescriptlang.o - [Sébastien Mischler](https://github.com/skarab42) ## License + SPDX-License-Identifier: (MIT OR CC0-1.0) \ No newline at end of file From 0bad58141c7b98aa4855577f781f5a164645c81b Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Fri, 31 Mar 2023 12:36:27 +0000 Subject: [PATCH 06/11] style: align with existing style --- source/literal-to-primitive-deep.d.ts | 44 +++++++++++++-------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/source/literal-to-primitive-deep.d.ts b/source/literal-to-primitive-deep.d.ts index 7f919e7b8..9d4a20bc7 100644 --- a/source/literal-to-primitive-deep.d.ts +++ b/source/literal-to-primitive-deep.d.ts @@ -2,28 +2,28 @@ import type {LiteralToPrimitive} from './literal-to-primitive'; import type {OmitIndexSignature} from './omit-index-signature'; /** - * Given a constant object, return a new object with the same keys but with all the values converted to primitives. - * @see LiteralToPrimitive - * - * Use-case: Deal with data that is imported from a JSON file. - * - * @example - * ``` - * import type { LiteralToPrimitiveDeep, TsConfigJson } from 'type-fest'; - * import tsconfig from 'path/to/tsconfig.json'; - * - * function doSomethingWithTSConfig(config: LiteralToPrimitiveDeep) { ... } - * - * // no casting is needed to pass the type check - * doSomethingWithTSConfig(tsconfig); - * - * // if LiteralToPrimitiveDeep is not used, you need to cast the imported data like this: - * doSomethingWithTSConfig(tsconfig as TsConfigJson); - * ``` - * - * @category Type - * @category Object - */ +Given a constant object, return a new object with the same keys but with all the values converted to primitives. +@see LiteralToPrimitive + +Use-case: Deal with data that is imported from a JSON file. + +@example +``` +import type { LiteralToPrimitiveDeep, TsConfigJson } from 'type-fest'; +import tsconfig from 'path/to/tsconfig.json'; + +function doSomethingWithTSConfig(config: LiteralToPrimitiveDeep) { ... } + +// No casting is needed to pass the type check +doSomethingWithTSConfig(tsconfig); + +// If LiteralToPrimitiveDeep is not used, you need to cast the imported data like this: +doSomethingWithTSConfig(tsconfig as TsConfigJson); +``` + +@category Type +@category Object +*/ export type LiteralToPrimitiveDeep = T extends object ? T extends Array ? Array> From b27668a03b5600e6688b7bb1152f2e63c313c3c4 Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Fri, 31 Mar 2023 12:40:42 +0000 Subject: [PATCH 07/11] doc: undo changes made my autoformatter --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 1b2ee25ce..6b0001d91 100644 --- a/readme.md +++ b/readme.md @@ -912,4 +912,4 @@ You can find some examples in the [TypeScript docs](https://www.typescriptlang.o ## License -SPDX-License-Identifier: (MIT OR CC0-1.0) \ No newline at end of file +SPDX-License-Identifier: (MIT OR CC0-1.0) From af53a6de48dfd5ee8d339cb556bd144df83573ed Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Mon, 3 Apr 2023 07:06:31 +0000 Subject: [PATCH 08/11] doc: rephrase the description for `LiteralToPrimitive` --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 6b0001d91..8164836fc 100644 --- a/readme.md +++ b/readme.md @@ -157,7 +157,7 @@ Click the type names for complete docs. - [`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. -- [`LiteralToPrimitiveDeep`](source/literal-to-primitive-deep.d.ts) - Like `LiteralToPrimitive` except that it converts the literal types deeply. +- [`LiteralToPrimitiveDeep`](source/literal-to-primitive-deep.d.ts) - Like `LiteralToPrimitive`, but it converts literal types inside an object or array deeply. - [`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. From 484d27a613a01673a8e5e2d8b39f1eec8a99cc07 Mon Sep 17 00:00:00 2001 From: Alvis Tang Date: Mon, 3 Apr 2023 07:10:16 +0000 Subject: [PATCH 09/11] doc: improve the documentation of LiteralToPrimitiveDeep in code --- source/literal-to-primitive-deep.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/literal-to-primitive-deep.d.ts b/source/literal-to-primitive-deep.d.ts index 9d4a20bc7..68c071d97 100644 --- a/source/literal-to-primitive-deep.d.ts +++ b/source/literal-to-primitive-deep.d.ts @@ -2,14 +2,15 @@ import type {LiteralToPrimitive} from './literal-to-primitive'; import type {OmitIndexSignature} from './omit-index-signature'; /** -Given a constant object, return a new object with the same keys but with all the values converted to primitives. +Like `LiteralToPrimitive`, but it converts literal types inside an object or array deeply. +i.e. Given a constant object, return a new object type with the same keys but with all the values converted to primitives. @see LiteralToPrimitive Use-case: Deal with data that is imported from a JSON file. @example ``` -import type { LiteralToPrimitiveDeep, TsConfigJson } from 'type-fest'; +import type {LiteralToPrimitiveDeep, TsConfigJson} from 'type-fest'; import tsconfig from 'path/to/tsconfig.json'; function doSomethingWithTSConfig(config: LiteralToPrimitiveDeep) { ... } From 5e17a5d57851c29d69412115d287c8e2b2046472 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Tue, 4 Apr 2023 15:51:33 +0900 Subject: [PATCH 10/11] Update literal-to-primitive-deep.d.ts --- source/literal-to-primitive-deep.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/source/literal-to-primitive-deep.d.ts b/source/literal-to-primitive-deep.d.ts index 68c071d97..e36ff04a9 100644 --- a/source/literal-to-primitive-deep.d.ts +++ b/source/literal-to-primitive-deep.d.ts @@ -2,8 +2,10 @@ import type {LiteralToPrimitive} from './literal-to-primitive'; import type {OmitIndexSignature} from './omit-index-signature'; /** -Like `LiteralToPrimitive`, but it converts literal types inside an object or array deeply. -i.e. Given a constant object, return a new object type with the same keys but with all the values converted to primitives. +Like `LiteralToPrimitive` except it converts literal types inside an object or array deeply. + +For example, given a constant object, it returns a new object type with the same keys but with all the values converted to primitives. + @see LiteralToPrimitive Use-case: Deal with data that is imported from a JSON file. From 2f11f6866e1a15a897b5e054c3c4c7d8bb5bf2b0 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Tue, 4 Apr 2023 15:51:57 +0900 Subject: [PATCH 11/11] Update readme.md --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 8164836fc..568548fcf 100644 --- a/readme.md +++ b/readme.md @@ -157,7 +157,7 @@ Click the type names for complete docs. - [`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. -- [`LiteralToPrimitiveDeep`](source/literal-to-primitive-deep.d.ts) - Like `LiteralToPrimitive`, but it converts literal types inside an object or array deeply. +- [`LiteralToPrimitiveDeep`](source/literal-to-primitive-deep.d.ts) - Like `LiteralToPrimitive` except it converts literal types inside an object or array deeply. - [`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.