72d48089bbf7ba86390cdff62cb9f96393978e9bb8999646c70bf8936e0379d65a5ad498c29cb3a2bb198d0564f8241ac2ac440693160241d8b03f40c87da3 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. [![Build Status](https://travis-ci.com/sindresorhus/type-fest.svg?branch=master)](https://travis-ci.com/sindresorhus/type-fest)
  14. [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
  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. 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).
  19. Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
  20. PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first.
  21. ## Install
  22. ```
  23. $ npm install type-fest
  24. ```
  25. *Requires TypeScript >=3.2*
  26. ## Usage
  27. ```ts
  28. import {Except} from 'type-fest';
  29. type Foo = {
  30. unicorn: string;
  31. rainbow: boolean;
  32. };
  33. type FooWithoutRainbow = Except<Foo, 'rainbow'>;
  34. //=> {unicorn: string}
  35. ```
  36. ## API
  37. Click the type names for complete docs.
  38. ### Basic
  39. - [`Primitive`](source/basic.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
  40. - [`Class`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
  41. - [`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`.
  42. - [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
  43. - [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
  44. - [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value.
  45. - [`ObservableLike`](source/basic.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
  46. ### Utilities
  47. - [`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).
  48. - [`Mutable`](source/mutable.d.ts) - Convert an object with `readonly` keys into a mutable object. The inverse of `Readonly<T>`.
  49. - [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type.
  50. - [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
  51. - [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys.
  52. - [`RequireExactlyOne`](source/require-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more.
  53. - [`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.
  54. - [`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.
  55. - [`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).
  56. - [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`.
  57. - [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
  58. - [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
  59. - [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
  60. ### Miscellaneous
  61. - [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file).
  62. ## Declined types
  63. *If we decline a type addition, we will make sure to document the better solution here.*
  64. - [`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.
  65. - [`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.
  66. ## Tips
  67. ### Built-in types
  68. There are many advanced types most users don't know about.
  69. - [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) - Make all properties in `T` optional.
  70. <details>
  71. <summary>
  72. Example
  73. </summary>
  74. [Playground](https://typescript-play.js.org/?target=6#code/KYOwrgtgBAMg9gcxsAbsANlA3gKClAeQDMiAaPKAEWACMwFz8BRAJxbhcagDEBDAF17ocAXxw4AliH7AWRXgGNgUAHJwAJsADCcEEQkJsFXgAcTK3hGAAuKAGd+LKQgDcFEx363wEGrLf46IjIaOi28EioGG5iOArovHZ2qhrAAIJmAEJgEuiaLEb4Jk4oAsoKuvoIYCwCErq2apo6egZQALyF+FCm5pY2UABETelmg1xFnrYAzAAM8xNQQZGh4cFR6AB0xEQUIm4UFa0IABRHVbYACrws-BJCADwjLVUAfACUXfhEHFBnug4oABrYAATygcCIhBoACtgAp+JsQaC7P9ju9Prhut0joCwCZ1GUAGpCMDKTrnAwAbWRPWSyMhKWalQMAF0Dtj8BIoSd8YSZCT0GSOu1OmAQJp9CBgOpPkc7uBgBzOfwABYSOybSnVWp3XQ0sF04FgxnPFkIVkdKB84mkpUUfCxbEsYD8GogKBqjUBKBiWIAen9UGut3u6CeqReBlePXQQQA7skwMl+HAoMU4CgJJoISB0ODeOmbvwIVC1cAcIGmdpzVApDI5IpgJscNL49WMiZsrl8id3lrzScsD0zBYrLZBgAVOCUOCdwa+95uIA)
  75. ```ts
  76. interface NodeConfig {
  77. appName: string;
  78. port: number;
  79. }
  80. class NodeAppBuilder {
  81. private configuration: NodeConfig = {
  82. appName: 'NodeApp',
  83. port: 3000
  84. };
  85. config(config: Partial<NodeConfig>) {
  86. type NodeConfigKey = keyof NodeConfig;
  87. for (const key of Object.keys(config) as NodeConfigKey[]) {
  88. const updateValue = config[key];
  89. if (updateValue === undefined) {
  90. continue;
  91. }
  92. this.configuration[key] = updateValue;
  93. }
  94. return this;
  95. }
  96. }
  97. // `Partial<NodeConfig>`` allows us to provide only a part of the
  98. // NodeConfig interface.
  99. new NodeAppBuilder().config({appName: 'ToDoApp'});
  100. ```
  101. </details>
  102. - [`Required<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1408-L1413) - Make all properties in `T` required.
  103. <details>
  104. <summary>
  105. Example
  106. </summary>
  107. [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA)
  108. ```ts
  109. interface ContactForm {
  110. email?: string;
  111. message?: string;
  112. }
  113. function submitContactForm(formData: Required<ContactForm>) {
  114. // Send the form data to the server.
  115. }
  116. submitContactForm({
  117. email: 'ex@mple.com',
  118. message: 'Hi! Could you tell me more about…',
  119. });
  120. // TypeScript error: missing property 'message'
  121. submitContactForm({
  122. email: 'ex@mple.com',
  123. });
  124. ```
  125. </details>
  126. - [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) - Make all properties in `T` readonly.
  127. <details>
  128. <summary>
  129. Example
  130. </summary>
  131. [Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA)
  132. ```ts
  133. enum LogLevel {
  134. Off,
  135. Debug,
  136. Error,
  137. Fatal
  138. };
  139. interface LoggerConfig {
  140. name: string;
  141. level: LogLevel;
  142. }
  143. class Logger {
  144. config: Readonly<LoggerConfig>;
  145. constructor({name, level}: LoggerConfig) {
  146. this.config = {name, level};
  147. Object.freeze(this.config);
  148. }
  149. }
  150. const config: LoggerConfig = {
  151. name: 'MyApp',
  152. level: LogLevel.Debug
  153. };
  154. const logger = new Logger(config);
  155. // TypeScript Error: cannot assign to read-only property.
  156. logger.config.level = LogLevel.Error;
  157. // We are able to edit config variable as we please.
  158. config.level = LogLevel.Error;
  159. ```
  160. </details>
  161. - [`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`.
  162. <details>
  163. <summary>
  164. Example
  165. </summary>
  166. [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA)
  167. ```ts
  168. interface Article {
  169. title: string;
  170. thumbnail: string;
  171. content: string;
  172. }
  173. // Creates new type out of the `Article` interface composed
  174. // from the Articles' two properties: `title` and `thumbnail`.
  175. // `ArticlePreview = {title: string; thumbnail: string}`
  176. type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;
  177. // Render a list of articles using only title and description.
  178. function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
  179. const articles = document.createElement('div');
  180. for (const preview of previews) {
  181. // Append preview to the articles.
  182. }
  183. return articles;
  184. }
  185. const articles = renderArticlePreviews([
  186. {
  187. title: 'TypeScript tutorial!',
  188. thumbnail: '/assets/ts.jpg'
  189. }
  190. ]);
  191. ```
  192. </details>
  193. - [`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`.
  194. <details>
  195. <summary>
  196. Example
  197. </summary>
  198. [Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA)
  199. ```ts
  200. // Positions of employees in our company.
  201. type MemberPosition = 'intern' | 'developer' | 'tech-lead';
  202. // Interface describing properties of a single employee.
  203. interface Employee {
  204. firstName: string;
  205. lastName: string;
  206. yearsOfExperience: number;
  207. }
  208. // Create an object that has all possible `MemberPosition` values set as keys.
  209. // Those keys will store a collection of Employees of the same position.
  210. const team: Record<MemberPosition, Employee[]> = {
  211. intern: [],
  212. developer: [],
  213. 'tech-lead': [],
  214. };
  215. // Our team has decided to help John with his dream of becoming Software Developer.
  216. team.intern.push({
  217. firstName: 'John',
  218. lastName: 'Doe',
  219. yearsOfExperience: 0
  220. });
  221. // `Record` forces you to initialize all of the property keys.
  222. // TypeScript Error: "tech-lead" property is missing
  223. const teamEmpty: Record<MemberPosition, null> = {
  224. intern: null,
  225. developer: null,
  226. };
  227. ```
  228. </details>
  229. - [`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`.
  230. <details>
  231. <summary>
  232. Example
  233. </summary>
  234. [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA)
  235. ```ts
  236. interface ServerConfig {
  237. port: null | string | number;
  238. }
  239. type RequestHandler = (request: Request, response: Response) => void;
  240. // Exclude `null` type from `null | string | number`.
  241. // In case the port is equal to `null`, we will use default value.
  242. function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
  243. if (typeof port === 'string') {
  244. return parseInt(port, 10);
  245. }
  246. return port;
  247. }
  248. function startServer(handler: RequestHandler, config: ServerConfig): void {
  249. const server = require('http').createServer(handler);
  250. const port = config.port === null ? 3000 : getPortValue(config.port);
  251. server.listen(port);
  252. }
  253. ```
  254. </details>
  255. - [`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`.
  256. <details>
  257. <summary>
  258. Example
  259. </summary>
  260. [Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA)
  261. ```ts
  262. declare function uniqueId(): number;
  263. const ID = Symbol('ID');
  264. interface Person {
  265. [ID]: number;
  266. name: string;
  267. age: number;
  268. }
  269. // Allows changing the person data as long as the property key is of string type.
  270. function changePersonData<
  271. Obj extends Person,
  272. Key extends Extract<keyof Person, string>,
  273. Value extends Obj[Key]
  274. > (obj: Obj, key: Key, value: Value): void {
  275. obj[key] = value;
  276. }
  277. // Tiny Andrew was born.
  278. const andrew = {
  279. [ID]: uniqueId(),
  280. name: 'Andrew',
  281. age: 0,
  282. };
  283. // Cool, we're fine with that.
  284. changePersonData(andrew, 'name', 'Pony');
  285. // Goverment didn't like the fact that you wanted to change your identity.
  286. changePersonData(andrew, ID, uniqueId());
  287. ```
  288. </details>
  289. - [`NonNullable<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1446-L1449) - Exclude `null` and `undefined` from `T`.
  290. <details>
  291. <summary>
  292. Example
  293. </summary>
  294. 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>)
  295. [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA)
  296. ```ts
  297. type PortNumber = string | number | null;
  298. /** Part of a class definition that is used to build a server */
  299. class ServerBuilder {
  300. portNumber!: NonNullable<PortNumber>;
  301. port(this: ServerBuilder, port: PortNumber): ServerBuilder {
  302. if (port == null) {
  303. this.portNumber = 8000;
  304. } else {
  305. this.portNumber = port;
  306. }
  307. return this;
  308. }
  309. }
  310. const serverBuilder = new ServerBuilder();
  311. serverBuilder
  312. .port('8000') // portNumber = '8000'
  313. .port(null) // portNumber = 8000
  314. .port(3000); // portNumber = 3000
  315. // TypeScript error
  316. serverBuilder.portNumber = null;
  317. ```
  318. </details>
  319. - [`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.
  320. <details>
  321. <summary>
  322. Example
  323. </summary>
  324. [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA)
  325. ```ts
  326. function shuffle(input: any[]): void {
  327. // Mutate array randomly changing its' elements indexes.
  328. }
  329. function callNTimes<Fn extends (...args: any[]) => any> (func: Fn, callCount: number) {
  330. // Type that represents the type of the received function parameters.
  331. type FunctionParameters = Parameters<Fn>;
  332. return function (...args: FunctionParameters) {
  333. for (let i = 0; i < callCount; i++) {
  334. func(...args);
  335. }
  336. }
  337. }
  338. const shuffleTwice = callNTimes(shuffle, 2);
  339. ```
  340. </details>
  341. - [`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.
  342. <details>
  343. <summary>
  344. Example
  345. </summary>
  346. [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA)
  347. ```ts
  348. class ArticleModel {
  349. title: string;
  350. content?: string;
  351. constructor(title: string) {
  352. this.title = title;
  353. }
  354. }
  355. class InstanceCache<T extends (new (...args: any[]) => any)> {
  356. private ClassConstructor: T;
  357. private cache: Map<string, InstanceType<T>> = new Map();
  358. constructor (ctr: T) {
  359. this.ClassConstructor = ctr;
  360. }
  361. getInstance (...args: ConstructorParameters<T>): InstanceType<T> {
  362. const hash = this.calculateArgumentsHash(...args);
  363. const existingInstance = this.cache.get(hash);
  364. if (existingInstance !== undefined) {
  365. return existingInstance;
  366. }
  367. return new this.ClassConstructor(...args);
  368. }
  369. private calculateArgumentsHash(...args: any[]): string {
  370. // Calculate hash.
  371. return 'hash';
  372. }
  373. }
  374. const articleCache = new InstanceCache(ArticleModel);
  375. const amazonArticle = articleCache.getInstance('Amazon forests burining!');
  376. ```
  377. </details>
  378. - [`ReturnType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1461-L1464) – Obtain the return type of a function type.
  379. <details>
  380. <summary>
  381. Example
  382. </summary>
  383. [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
  384. ```ts
  385. /** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
  386. function mapIter<
  387. Elem,
  388. Func extends (elem: Elem) => any,
  389. Ret extends ReturnType<Func>
  390. >(iter: Iterable<Elem>, callback: Func): Ret[] {
  391. const mapped: Ret[] = [];
  392. for (const elem of iter) {
  393. mapped.push(callback(elem));
  394. }
  395. return mapped;
  396. }
  397. const setObject: Set<string> = new Set();
  398. const mapObject: Map<number, string> = new Map();
  399. mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]
  400. mapIter(mapObject, ([key, value]: [number, string]) => {
  401. return key % 2 === 0 ? value : 'Odd';
  402. }); // string[]
  403. ```
  404. </details>
  405. - [`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.
  406. <details>
  407. <summary>
  408. Example
  409. </summary>
  410. [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
  411. ```ts
  412. class IdleService {
  413. doNothing (): void {}
  414. }
  415. class News {
  416. title: string;
  417. content: string;
  418. constructor(title: string, content: string) {
  419. this.title = title;
  420. this.content = content;
  421. }
  422. }
  423. const instanceCounter: Map<Function, number> = new Map();
  424. interface Constructor {
  425. new(...args: any[]): any;
  426. }
  427. // Keep track how many instances of `Constr` constructor have been created.
  428. function getInstance<
  429. Constr extends Constructor,
  430. Args extends ConstructorParameters<Constr>
  431. >(constructor: Constr, ...args: Args): InstanceType<Constr> {
  432. let count = instanceCounter.get(constructor) || 0;
  433. const instance = new constructor(...args);
  434. instanceCounter.set(constructor, count + 1);
  435. console.log(`Created ${count + 1} instances of ${Constr.name} class`);
  436. return instance;
  437. }
  438. const idleService = getInstance(IdleService);
  439. // Will log: `Created 1 instances of IdleService class`
  440. const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...');
  441. // Will log: `Created 1 instances of News class`
  442. ```
  443. </details>
  444. - [`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.
  445. <details>
  446. <summary>
  447. Example
  448. </summary>
  449. [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA)
  450. ```ts
  451. interface Animal {
  452. imageUrl: string;
  453. species: string;
  454. images: string[];
  455. paragraphs: string[];
  456. }
  457. // Creates new type with all properties of the `Animal` interface
  458. // except 'images' and 'paragraphs' properties. We can use this
  459. // type to render small hover tooltip for a wiki entry list.
  460. type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;
  461. function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
  462. const container = document.createElement('div');
  463. // Internal implementation.
  464. return container;
  465. }
  466. ```
  467. </details>
  468. You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types).
  469. ## Maintainers
  470. - [Sindre Sorhus](https://github.com/sindresorhus)
  471. - [Jarek Radosz](https://github.com/CvX)
  472. - [Dimitri Benin](https://github.com/BendingBender)
  473. ## License
  474. (MIT OR CC0-1.0)
  475. ---
  476. <div align="center">
  477. <b>
  478. <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>
  479. </b>
  480. <br>
  481. <sub>
  482. Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
  483. </sub>
  484. </div>