1 | <div align="center">
|
---|
2 | <br>
|
---|
3 | <br>
|
---|
4 | <img src="media/logo.svg" alt="type-fest" height="300">
|
---|
5 | <br>
|
---|
6 | <br>
|
---|
7 | <b>A collection of essential TypeScript types</b>
|
---|
8 | <br>
|
---|
9 | <hr>
|
---|
10 | </div>
|
---|
11 | <br>
|
---|
12 | <br>
|
---|
13 |
|
---|
14 | [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://giphy.com/gifs/illustration-rainbow-unicorn-26AHG5KGFxSkUWw1i)
|
---|
15 | <!-- Commented out until they actually show anything
|
---|
16 | [![npm dependents](https://badgen.net/npm/dependents/type-fest)](https://www.npmjs.com/package/type-fest?activeTab=dependents) [![npm downloads](https://badgen.net/npm/dt/type-fest)](https://www.npmjs.com/package/type-fest)
|
---|
17 | -->
|
---|
18 |
|
---|
19 | Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md).
|
---|
20 |
|
---|
21 | Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
|
---|
22 |
|
---|
23 | PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first.
|
---|
24 |
|
---|
25 | ## Install
|
---|
26 |
|
---|
27 | ```
|
---|
28 | $ npm install type-fest
|
---|
29 | ```
|
---|
30 |
|
---|
31 | *Requires TypeScript >=3.4*
|
---|
32 |
|
---|
33 | ## Usage
|
---|
34 |
|
---|
35 | ```ts
|
---|
36 | import {Except} from 'type-fest';
|
---|
37 |
|
---|
38 | type Foo = {
|
---|
39 | unicorn: string;
|
---|
40 | rainbow: boolean;
|
---|
41 | };
|
---|
42 |
|
---|
43 | type FooWithoutRainbow = Except<Foo, 'rainbow'>;
|
---|
44 | //=> {unicorn: string}
|
---|
45 | ```
|
---|
46 |
|
---|
47 | ## API
|
---|
48 |
|
---|
49 | Click the type names for complete docs.
|
---|
50 |
|
---|
51 | ### Basic
|
---|
52 |
|
---|
53 | - [`Primitive`](source/basic.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
|
---|
54 | - [`Class`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
|
---|
55 | - [`TypedArray`](source/basic.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
|
---|
56 | - [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
|
---|
57 | - [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
|
---|
58 | - [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value.
|
---|
59 | - [`ObservableLike`](source/basic.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
|
---|
60 |
|
---|
61 | ### Utilities
|
---|
62 |
|
---|
63 | - [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type).
|
---|
64 | - [`Mutable`](source/mutable.d.ts) - Convert an object with `readonly` keys into a mutable object. The inverse of `Readonly<T>`.
|
---|
65 | - [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type.
|
---|
66 | - [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
|
---|
67 | - [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys.
|
---|
68 | - [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more.
|
---|
69 | - [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) if you only need one level deep.
|
---|
70 | - [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) if you only need one level deep.
|
---|
71 | - [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729).
|
---|
72 | - [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`.
|
---|
73 | - [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
|
---|
74 | - [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
|
---|
75 | - [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
|
---|
76 | - [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from.
|
---|
77 | - [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise`.
|
---|
78 | - [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`.
|
---|
79 | - [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type.
|
---|
80 | - [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type.
|
---|
81 | - [`ConditionalExcept`](source/conditional-except.d.ts) - Like `Omit` except it removes properties from a shape where the values extend the given `Condition` type.
|
---|
82 | - [`UnionToIntersection`](source/union-to-intersection.d.ts) - Convert a union type to an intersection type.
|
---|
83 | - [`Stringified`](source/stringified.d.ts) - Create a type with the keys of the given type changed to `string` type.
|
---|
84 | - [`FixedLengthArray`](source/fixed-length-array.d.ts) - Create a type that represents an array of the given type and length.
|
---|
85 | - [`IterableElement`](source/iterable-element.d.ts) - Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
|
---|
86 | - [`Entry`](source/entry.d.ts) - Create a type that represents the type of an entry of a collection.
|
---|
87 | - [`Entries`](source/entries.d.ts) - Create a type that represents the type of the entries of a collection.
|
---|
88 | - [`SetReturnType`](source/set-return-type.d.ts) - Create a function type with a return type of your choice and the same parameters as the given function type.
|
---|
89 | - [`Asyncify`](source/asyncify.d.ts) - Create an async version of the given function type.
|
---|
90 |
|
---|
91 | ### Template literal types
|
---|
92 |
|
---|
93 | *Note:* These require [TypeScript 4.1 or newer](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#template-literal-types).
|
---|
94 |
|
---|
95 | - [`CamelCase`](ts41/camel-case.d.ts) – Convert a string literal to camel-case (`fooBar`).
|
---|
96 | - [`KebabCase`](ts41/kebab-case.d.ts) – Convert a string literal to kebab-case (`foo-bar`).
|
---|
97 | - [`PascalCase`](ts41/pascal-case.d.ts) – Converts a string literal to pascal-case (`FooBar`)
|
---|
98 | - [`SnakeCase`](ts41/snake-case.d.ts) – Convert a string literal to snake-case (`foo_bar`).
|
---|
99 | - [`DelimiterCase`](ts41/delimiter-case.d.ts) – Convert a string literal to a custom string delimiter casing.
|
---|
100 |
|
---|
101 | ### Miscellaneous
|
---|
102 |
|
---|
103 | - [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file).
|
---|
104 | - [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 3.7).
|
---|
105 |
|
---|
106 | ## Declined types
|
---|
107 |
|
---|
108 | *If we decline a type addition, we will make sure to document the better solution here.*
|
---|
109 |
|
---|
110 | - [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The PR 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.
|
---|
111 | - [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary<number>` vs `Record<string, number>`) from [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now.
|
---|
112 | - [`SubType`](https://github.com/sindresorhus/type-fest/issues/22) - The type is powerful, but lacks good use-cases and is prone to misuse.
|
---|
113 | - [`ExtractProperties` and `ExtractMethods`](https://github.com/sindresorhus/type-fest/pull/4) - The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies.
|
---|
114 |
|
---|
115 | ## Tips
|
---|
116 |
|
---|
117 | ### Built-in types
|
---|
118 |
|
---|
119 | There are many advanced types most users don't know about.
|
---|
120 |
|
---|
121 | - [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) - Make all properties in `T` optional.
|
---|
122 | <details>
|
---|
123 | <summary>
|
---|
124 | Example
|
---|
125 | </summary>
|
---|
126 |
|
---|
127 | [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA)
|
---|
128 |
|
---|
129 | ```ts
|
---|
130 | interface NodeConfig {
|
---|
131 | appName: string;
|
---|
132 | port: number;
|
---|
133 | }
|
---|
134 |
|
---|
135 | class NodeAppBuilder {
|
---|
136 | private configuration: NodeConfig = {
|
---|
137 | appName: 'NodeApp',
|
---|
138 | port: 3000
|
---|
139 | };
|
---|
140 |
|
---|
141 | private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) {
|
---|
142 | this.configuration[key] = value;
|
---|
143 | }
|
---|
144 |
|
---|
145 | config(config: Partial<NodeConfig>) {
|
---|
146 | type NodeConfigKey = keyof NodeConfig;
|
---|
147 |
|
---|
148 | for (const key of Object.keys(config) as NodeConfigKey[]) {
|
---|
149 | const updateValue = config[key];
|
---|
150 |
|
---|
151 | if (updateValue === undefined) {
|
---|
152 | continue;
|
---|
153 | }
|
---|
154 |
|
---|
155 | this.updateConfig(key, updateValue);
|
---|
156 | }
|
---|
157 |
|
---|
158 | return this;
|
---|
159 | }
|
---|
160 | }
|
---|
161 |
|
---|
162 | // `Partial<NodeConfig>`` allows us to provide only a part of the
|
---|
163 | // NodeConfig interface.
|
---|
164 | new NodeAppBuilder().config({appName: 'ToDoApp'});
|
---|
165 | ```
|
---|
166 | </details>
|
---|
167 |
|
---|
168 | - [`Required<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1408-L1413) - Make all properties in `T` required.
|
---|
169 | <details>
|
---|
170 | <summary>
|
---|
171 | Example
|
---|
172 | </summary>
|
---|
173 |
|
---|
174 | [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA)
|
---|
175 |
|
---|
176 | ```ts
|
---|
177 | interface ContactForm {
|
---|
178 | email?: string;
|
---|
179 | message?: string;
|
---|
180 | }
|
---|
181 |
|
---|
182 | function submitContactForm(formData: Required<ContactForm>) {
|
---|
183 | // Send the form data to the server.
|
---|
184 | }
|
---|
185 |
|
---|
186 | submitContactForm({
|
---|
187 | email: 'ex@mple.com',
|
---|
188 | message: 'Hi! Could you tell me more about…',
|
---|
189 | });
|
---|
190 |
|
---|
191 | // TypeScript error: missing property 'message'
|
---|
192 | submitContactForm({
|
---|
193 | email: 'ex@mple.com',
|
---|
194 | });
|
---|
195 | ```
|
---|
196 | </details>
|
---|
197 |
|
---|
198 | - [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) - Make all properties in `T` readonly.
|
---|
199 | <details>
|
---|
200 | <summary>
|
---|
201 | Example
|
---|
202 | </summary>
|
---|
203 |
|
---|
204 | [Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA)
|
---|
205 |
|
---|
206 | ```ts
|
---|
207 | enum LogLevel {
|
---|
208 | Off,
|
---|
209 | Debug,
|
---|
210 | Error,
|
---|
211 | Fatal
|
---|
212 | };
|
---|
213 |
|
---|
214 | interface LoggerConfig {
|
---|
215 | name: string;
|
---|
216 | level: LogLevel;
|
---|
217 | }
|
---|
218 |
|
---|
219 | class Logger {
|
---|
220 | config: Readonly<LoggerConfig>;
|
---|
221 |
|
---|
222 | constructor({name, level}: LoggerConfig) {
|
---|
223 | this.config = {name, level};
|
---|
224 | Object.freeze(this.config);
|
---|
225 | }
|
---|
226 | }
|
---|
227 |
|
---|
228 | const config: LoggerConfig = {
|
---|
229 | name: 'MyApp',
|
---|
230 | level: LogLevel.Debug
|
---|
231 | };
|
---|
232 |
|
---|
233 | const logger = new Logger(config);
|
---|
234 |
|
---|
235 | // TypeScript Error: cannot assign to read-only property.
|
---|
236 | logger.config.level = LogLevel.Error;
|
---|
237 |
|
---|
238 | // We are able to edit config variable as we please.
|
---|
239 | config.level = LogLevel.Error;
|
---|
240 | ```
|
---|
241 | </details>
|
---|
242 |
|
---|
243 | - [`Pick<T, K>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1422-L1427) - From `T`, pick a set of properties whose keys are in the union `K`.
|
---|
244 | <details>
|
---|
245 | <summary>
|
---|
246 | Example
|
---|
247 | </summary>
|
---|
248 |
|
---|
249 | [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA)
|
---|
250 |
|
---|
251 | ```ts
|
---|
252 | interface Article {
|
---|
253 | title: string;
|
---|
254 | thumbnail: string;
|
---|
255 | content: string;
|
---|
256 | }
|
---|
257 |
|
---|
258 | // Creates new type out of the `Article` interface composed
|
---|
259 | // from the Articles' two properties: `title` and `thumbnail`.
|
---|
260 | // `ArticlePreview = {title: string; thumbnail: string}`
|
---|
261 | type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;
|
---|
262 |
|
---|
263 | // Render a list of articles using only title and description.
|
---|
264 | function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
|
---|
265 | const articles = document.createElement('div');
|
---|
266 |
|
---|
267 | for (const preview of previews) {
|
---|
268 | // Append preview to the articles.
|
---|
269 | }
|
---|
270 |
|
---|
271 | return articles;
|
---|
272 | }
|
---|
273 |
|
---|
274 | const articles = renderArticlePreviews([
|
---|
275 | {
|
---|
276 | title: 'TypeScript tutorial!',
|
---|
277 | thumbnail: '/assets/ts.jpg'
|
---|
278 | }
|
---|
279 | ]);
|
---|
280 | ```
|
---|
281 | </details>
|
---|
282 |
|
---|
283 | - [`Record<K, T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434) - Construct a type with a set of properties `K` of type `T`.
|
---|
284 | <details>
|
---|
285 | <summary>
|
---|
286 | Example
|
---|
287 | </summary>
|
---|
288 |
|
---|
289 | [Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA)
|
---|
290 |
|
---|
291 | ```ts
|
---|
292 | // Positions of employees in our company.
|
---|
293 | type MemberPosition = 'intern' | 'developer' | 'tech-lead';
|
---|
294 |
|
---|
295 | // Interface describing properties of a single employee.
|
---|
296 | interface Employee {
|
---|
297 | firstName: string;
|
---|
298 | lastName: string;
|
---|
299 | yearsOfExperience: number;
|
---|
300 | }
|
---|
301 |
|
---|
302 | // Create an object that has all possible `MemberPosition` values set as keys.
|
---|
303 | // Those keys will store a collection of Employees of the same position.
|
---|
304 | const team: Record<MemberPosition, Employee[]> = {
|
---|
305 | intern: [],
|
---|
306 | developer: [],
|
---|
307 | 'tech-lead': [],
|
---|
308 | };
|
---|
309 |
|
---|
310 | // Our team has decided to help John with his dream of becoming Software Developer.
|
---|
311 | team.intern.push({
|
---|
312 | firstName: 'John',
|
---|
313 | lastName: 'Doe',
|
---|
314 | yearsOfExperience: 0
|
---|
315 | });
|
---|
316 |
|
---|
317 | // `Record` forces you to initialize all of the property keys.
|
---|
318 | // TypeScript Error: "tech-lead" property is missing
|
---|
319 | const teamEmpty: Record<MemberPosition, null> = {
|
---|
320 | intern: null,
|
---|
321 | developer: null,
|
---|
322 | };
|
---|
323 | ```
|
---|
324 | </details>
|
---|
325 |
|
---|
326 | - [`Exclude<T, U>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1436-L1439) - Exclude from `T` those types that are assignable to `U`.
|
---|
327 | <details>
|
---|
328 | <summary>
|
---|
329 | Example
|
---|
330 | </summary>
|
---|
331 |
|
---|
332 | [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA)
|
---|
333 |
|
---|
334 | ```ts
|
---|
335 | interface ServerConfig {
|
---|
336 | port: null | string | number;
|
---|
337 | }
|
---|
338 |
|
---|
339 | type RequestHandler = (request: Request, response: Response) => void;
|
---|
340 |
|
---|
341 | // Exclude `null` type from `null | string | number`.
|
---|
342 | // In case the port is equal to `null`, we will use default value.
|
---|
343 | function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
|
---|
344 | if (typeof port === 'string') {
|
---|
345 | return parseInt(port, 10);
|
---|
346 | }
|
---|
347 |
|
---|
348 | return port;
|
---|
349 | }
|
---|
350 |
|
---|
351 | function startServer(handler: RequestHandler, config: ServerConfig): void {
|
---|
352 | const server = require('http').createServer(handler);
|
---|
353 |
|
---|
354 | const port = config.port === null ? 3000 : getPortValue(config.port);
|
---|
355 | server.listen(port);
|
---|
356 | }
|
---|
357 | ```
|
---|
358 | </details>
|
---|
359 |
|
---|
360 | - [`Extract<T, U>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1441-L1444) - Extract from `T` those types that are assignable to `U`.
|
---|
361 | <details>
|
---|
362 | <summary>
|
---|
363 | Example
|
---|
364 | </summary>
|
---|
365 |
|
---|
366 | [Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA)
|
---|
367 |
|
---|
368 | ```ts
|
---|
369 | declare function uniqueId(): number;
|
---|
370 |
|
---|
371 | const ID = Symbol('ID');
|
---|
372 |
|
---|
373 | interface Person {
|
---|
374 | [ID]: number;
|
---|
375 | name: string;
|
---|
376 | age: number;
|
---|
377 | }
|
---|
378 |
|
---|
379 | // Allows changing the person data as long as the property key is of string type.
|
---|
380 | function changePersonData<
|
---|
381 | Obj extends Person,
|
---|
382 | Key extends Extract<keyof Person, string>,
|
---|
383 | Value extends Obj[Key]
|
---|
384 | > (obj: Obj, key: Key, value: Value): void {
|
---|
385 | obj[key] = value;
|
---|
386 | }
|
---|
387 |
|
---|
388 | // Tiny Andrew was born.
|
---|
389 | const andrew = {
|
---|
390 | [ID]: uniqueId(),
|
---|
391 | name: 'Andrew',
|
---|
392 | age: 0,
|
---|
393 | };
|
---|
394 |
|
---|
395 | // Cool, we're fine with that.
|
---|
396 | changePersonData(andrew, 'name', 'Pony');
|
---|
397 |
|
---|
398 | // Goverment didn't like the fact that you wanted to change your identity.
|
---|
399 | changePersonData(andrew, ID, uniqueId());
|
---|
400 | ```
|
---|
401 | </details>
|
---|
402 |
|
---|
403 | - [`NonNullable<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1446-L1449) - Exclude `null` and `undefined` from `T`.
|
---|
404 | <details>
|
---|
405 | <summary>
|
---|
406 | Example
|
---|
407 | </summary>
|
---|
408 | Works with <code>strictNullChecks</code> set to <code>true</code>. (Read more <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html">here</a>)
|
---|
409 |
|
---|
410 | [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA)
|
---|
411 |
|
---|
412 | ```ts
|
---|
413 | type PortNumber = string | number | null;
|
---|
414 |
|
---|
415 | /** Part of a class definition that is used to build a server */
|
---|
416 | class ServerBuilder {
|
---|
417 | portNumber!: NonNullable<PortNumber>;
|
---|
418 |
|
---|
419 | port(this: ServerBuilder, port: PortNumber): ServerBuilder {
|
---|
420 | if (port == null) {
|
---|
421 | this.portNumber = 8000;
|
---|
422 | } else {
|
---|
423 | this.portNumber = port;
|
---|
424 | }
|
---|
425 |
|
---|
426 | return this;
|
---|
427 | }
|
---|
428 | }
|
---|
429 |
|
---|
430 | const serverBuilder = new ServerBuilder();
|
---|
431 |
|
---|
432 | serverBuilder
|
---|
433 | .port('8000') // portNumber = '8000'
|
---|
434 | .port(null) // portNumber = 8000
|
---|
435 | .port(3000); // portNumber = 3000
|
---|
436 |
|
---|
437 | // TypeScript error
|
---|
438 | serverBuilder.portNumber = null;
|
---|
439 | ```
|
---|
440 | </details>
|
---|
441 |
|
---|
442 | - [`Parameters<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1451-L1454) - Obtain the parameters of a function type in a tuple.
|
---|
443 | <details>
|
---|
444 | <summary>
|
---|
445 | Example
|
---|
446 | </summary>
|
---|
447 |
|
---|
448 | [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA)
|
---|
449 |
|
---|
450 | ```ts
|
---|
451 | function shuffle(input: any[]): void {
|
---|
452 | // Mutate array randomly changing its' elements indexes.
|
---|
453 | }
|
---|
454 |
|
---|
455 | function callNTimes<Fn extends (...args: any[]) => any> (func: Fn, callCount: number) {
|
---|
456 | // Type that represents the type of the received function parameters.
|
---|
457 | type FunctionParameters = Parameters<Fn>;
|
---|
458 |
|
---|
459 | return function (...args: FunctionParameters) {
|
---|
460 | for (let i = 0; i < callCount; i++) {
|
---|
461 | func(...args);
|
---|
462 | }
|
---|
463 | }
|
---|
464 | }
|
---|
465 |
|
---|
466 | const shuffleTwice = callNTimes(shuffle, 2);
|
---|
467 | ```
|
---|
468 | </details>
|
---|
469 |
|
---|
470 | - [`ConstructorParameters<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1456-L1459) - Obtain the parameters of a constructor function type in a tuple.
|
---|
471 | <details>
|
---|
472 | <summary>
|
---|
473 | Example
|
---|
474 | </summary>
|
---|
475 |
|
---|
476 | [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA)
|
---|
477 |
|
---|
478 | ```ts
|
---|
479 | class ArticleModel {
|
---|
480 | title: string;
|
---|
481 | content?: string;
|
---|
482 |
|
---|
483 | constructor(title: string) {
|
---|
484 | this.title = title;
|
---|
485 | }
|
---|
486 | }
|
---|
487 |
|
---|
488 | class InstanceCache<T extends (new (...args: any[]) => any)> {
|
---|
489 | private ClassConstructor: T;
|
---|
490 | private cache: Map<string, InstanceType<T>> = new Map();
|
---|
491 |
|
---|
492 | constructor (ctr: T) {
|
---|
493 | this.ClassConstructor = ctr;
|
---|
494 | }
|
---|
495 |
|
---|
496 | getInstance (...args: ConstructorParameters<T>): InstanceType<T> {
|
---|
497 | const hash = this.calculateArgumentsHash(...args);
|
---|
498 |
|
---|
499 | const existingInstance = this.cache.get(hash);
|
---|
500 | if (existingInstance !== undefined) {
|
---|
501 | return existingInstance;
|
---|
502 | }
|
---|
503 |
|
---|
504 | return new this.ClassConstructor(...args);
|
---|
505 | }
|
---|
506 |
|
---|
507 | private calculateArgumentsHash(...args: any[]): string {
|
---|
508 | // Calculate hash.
|
---|
509 | return 'hash';
|
---|
510 | }
|
---|
511 | }
|
---|
512 |
|
---|
513 | const articleCache = new InstanceCache(ArticleModel);
|
---|
514 | const amazonArticle = articleCache.getInstance('Amazon forests burining!');
|
---|
515 | ```
|
---|
516 | </details>
|
---|
517 |
|
---|
518 | - [`ReturnType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1461-L1464) – Obtain the return type of a function type.
|
---|
519 | <details>
|
---|
520 | <summary>
|
---|
521 | Example
|
---|
522 | </summary>
|
---|
523 |
|
---|
524 | [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
|
---|
525 |
|
---|
526 | ```ts
|
---|
527 | /** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
|
---|
528 | function mapIter<
|
---|
529 | Elem,
|
---|
530 | Func extends (elem: Elem) => any,
|
---|
531 | Ret extends ReturnType<Func>
|
---|
532 | >(iter: Iterable<Elem>, callback: Func): Ret[] {
|
---|
533 | const mapped: Ret[] = [];
|
---|
534 |
|
---|
535 | for (const elem of iter) {
|
---|
536 | mapped.push(callback(elem));
|
---|
537 | }
|
---|
538 |
|
---|
539 | return mapped;
|
---|
540 | }
|
---|
541 |
|
---|
542 | const setObject: Set<string> = new Set();
|
---|
543 | const mapObject: Map<number, string> = new Map();
|
---|
544 |
|
---|
545 | mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]
|
---|
546 |
|
---|
547 | mapIter(mapObject, ([key, value]: [number, string]) => {
|
---|
548 | return key % 2 === 0 ? value : 'Odd';
|
---|
549 | }); // string[]
|
---|
550 | ```
|
---|
551 | </details>
|
---|
552 |
|
---|
553 | - [`InstanceType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1466-L1469) – Obtain the instance type of a constructor function type.
|
---|
554 | <details>
|
---|
555 | <summary>
|
---|
556 | Example
|
---|
557 | </summary>
|
---|
558 |
|
---|
559 | [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
|
---|
560 |
|
---|
561 | ```ts
|
---|
562 | class IdleService {
|
---|
563 | doNothing (): void {}
|
---|
564 | }
|
---|
565 |
|
---|
566 | class News {
|
---|
567 | title: string;
|
---|
568 | content: string;
|
---|
569 |
|
---|
570 | constructor(title: string, content: string) {
|
---|
571 | this.title = title;
|
---|
572 | this.content = content;
|
---|
573 | }
|
---|
574 | }
|
---|
575 |
|
---|
576 | const instanceCounter: Map<Function, number> = new Map();
|
---|
577 |
|
---|
578 | interface Constructor {
|
---|
579 | new(...args: any[]): any;
|
---|
580 | }
|
---|
581 |
|
---|
582 | // Keep track how many instances of `Constr` constructor have been created.
|
---|
583 | function getInstance<
|
---|
584 | Constr extends Constructor,
|
---|
585 | Args extends ConstructorParameters<Constr>
|
---|
586 | >(constructor: Constr, ...args: Args): InstanceType<Constr> {
|
---|
587 | let count = instanceCounter.get(constructor) || 0;
|
---|
588 |
|
---|
589 | const instance = new constructor(...args);
|
---|
590 |
|
---|
591 | instanceCounter.set(constructor, count + 1);
|
---|
592 |
|
---|
593 | console.log(`Created ${count + 1} instances of ${Constr.name} class`);
|
---|
594 |
|
---|
595 | return instance;
|
---|
596 | }
|
---|
597 |
|
---|
598 |
|
---|
599 | const idleService = getInstance(IdleService);
|
---|
600 | // Will log: `Created 1 instances of IdleService class`
|
---|
601 | const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...');
|
---|
602 | // Will log: `Created 1 instances of News class`
|
---|
603 | ```
|
---|
604 | </details>
|
---|
605 |
|
---|
606 | - [`Omit<T, K>`](https://github.com/microsoft/TypeScript/blob/71af02f7459dc812e85ac31365bfe23daf14b4e4/src/lib/es5.d.ts#L1446) – Constructs a type by picking all properties from T and then removing K.
|
---|
607 | <details>
|
---|
608 | <summary>
|
---|
609 | Example
|
---|
610 | </summary>
|
---|
611 |
|
---|
612 | [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA)
|
---|
613 |
|
---|
614 | ```ts
|
---|
615 | interface Animal {
|
---|
616 | imageUrl: string;
|
---|
617 | species: string;
|
---|
618 | images: string[];
|
---|
619 | paragraphs: string[];
|
---|
620 | }
|
---|
621 |
|
---|
622 | // Creates new type with all properties of the `Animal` interface
|
---|
623 | // except 'images' and 'paragraphs' properties. We can use this
|
---|
624 | // type to render small hover tooltip for a wiki entry list.
|
---|
625 | type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;
|
---|
626 |
|
---|
627 | function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
|
---|
628 | const container = document.createElement('div');
|
---|
629 | // Internal implementation.
|
---|
630 | return container;
|
---|
631 | }
|
---|
632 | ```
|
---|
633 | </details>
|
---|
634 |
|
---|
635 | You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types).
|
---|
636 |
|
---|
637 | ## Maintainers
|
---|
638 |
|
---|
639 | - [Sindre Sorhus](https://github.com/sindresorhus)
|
---|
640 | - [Jarek Radosz](https://github.com/CvX)
|
---|
641 | - [Dimitri Benin](https://github.com/BendingBender)
|
---|
642 | - [Pelle Wessman](https://github.com/voxpelli)
|
---|
643 |
|
---|
644 | ## License
|
---|
645 |
|
---|
646 | (MIT OR CC0-1.0)
|
---|
647 |
|
---|
648 | ---
|
---|
649 |
|
---|
650 | <div align="center">
|
---|
651 | <b>
|
---|
652 | <a href="https://tidelift.com/subscription/pkg/npm-type-fest?utm_source=npm-type-fest&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
|
---|
653 | </b>
|
---|
654 | <br>
|
---|
655 | <sub>
|
---|
656 | Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
|
---|
657 | </sub>
|
---|
658 | </div>
|
---|