Title: Tag types · Issue #4895 · microsoft/TypeScript · GitHub
Open Graph Title: Tag types · Issue #4895 · microsoft/TypeScript
X Title: Tag types · Issue #4895 · microsoft/TypeScript
Description: Problem There is no straight way to encode a predicate (some checking) about a value in its type. Details There are situations when a value has to pass some sort of check/validation prior to being used. For example: a min/max functions c...
Open Graph Description: Problem There is no straight way to encode a predicate (some checking) about a value in its type. Details There are situations when a value has to pass some sort of check/validation prior to being ...
X Description: Problem There is no straight way to encode a predicate (some checking) about a value in its type. Details There are situations when a value has to pass some sort of check/validation prior to being ...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/4895
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Tag types","articleBody":"### Problem\n- There is no straight way to encode a predicate (some checking) about a value in its type.\n### Details\n\nThere are situations when a value has to pass some sort of check/validation prior to being used. For example: a min/max functions can only operate on a non-empty array so there must be a check if a given array has any elements. If we pass a plain array that might as well be empty, then we need to account for such case inside the min/max functions, by doing one of the following:\n- crashing\n- returning undefined\n- returning a given default value\n\nThis way the calling side has to deal with the consequences of min/max being called yet not being able to deliver.\n\n``` typescript\nfunction min\u003ca>(values: a[], isGreater: (one: a, another: a) => boolean) : a {\n if (values.length \u003c 1) { throw Error('Array is empty.'); }\n // ...\n}\nvar found;\ntry {\n found = min([]);\n} catch (e) {\n found = undefined;\n}\n```\n### Solution\n\nA better idea is to leverage the type system to rule out a possibility of the min function being called with an empty array. In order to do so we might consider so called tag types. \n\nA **tag type** is a qualifier type that indicates that some predicate about a value it is associated with holds true.\n\n``` typescript\n\nconst enum AsNonEmpty {} // a tag type that encodes that a check for being non-empty was passed\n\nfunction min\u003ca>(values: a[] & AsNonEmpty) : a {\n // only values that are tagged with AsNonEmpty can be passed to this function\n // the type system is responsible for enforcing this constraint\n // a guarantee by the type system that only non-empty array will be passed makes\n // implementation of this function simpler because only one main case needs be considered\n // leaving empty-case situations outside of this function\n}\n\nmin([]); // \u003c-- compile error, tag is missing, the argument is not known to be non-empty\nmin([1, 2]); // \u003c-- compile error, tag is missing again, the argument is not know to be non-empty\n```\n\nit's up to the developer in what circumstances an array gets its AsNonEmpty tag, which can be something like:\n\n``` typescript\n// guarntee is given by the server, so we always trust the data that comes from it\ninterface GuaranteedByServer {\n values: number[] & AsNonEmpty;\n}\n\n```\n\nAlso tags can be assigned at runtime:\n\n``` typescript\n\nfunction asNonEmpty(values: a[]) : (a[] & AsNonEmpty) | void {\n return values.length > 0 ? \u003ca[] & AsNonEmpty> : undefined;\n}\n\nfunction isVoid\u003ca>(value: a | void) : value is void {\n return value == null;\n}\n\nvar values = asNonEmpty(Math.random() > 0.5 ? [1, 2, 3] : []);\nif (isVoid(values)) {\n // there are no elements in the array, so we can't call min\n var niceTry = min(values); // \u003c-- compile error; \n} else {\n var found = min(values); // \u003c-- ok, tag is there, safe to call\n}\n\n```\n\nAs was shown in the current version (1.6) an empty const enum type can be used as a marker type (AsNonEmpty in the above example), because\n- enums might not have any members and yet be different from the empty type\n- enums are branded (not assignable to one another)\n\nHowever enums have their limitations:\n- enum is assignable by numbers\n- enum cannot hold a type parameter\n- enum cannot have members\n\nA few more examples of what tag type can encode:\n- `string & AsTrimmed & AsLowerCased & AsAtLeast3CharLong`\n- `number & AsNonNegative & AsEven`\n- `date & AsInWinter & AsFirstDayOfMonth`\n\nCustom types can also be augmented with tags. This is especially useful when the types are defined outside of the project and developers can't alter them.\n- `User & AsHavingClearance`\n\n**ALSO NOTE**: In a way tag types are similar to boolean properties (flags), BUT they get type-erased and carry no rutime overhead whatsoever being a good example of a zero-cost abstraction.\n\n**UPDATED:**\n\nAlso tag types can be used as units of measure in a way:\n- `string & AsEmail`, `string & AsFirstName`:\n\n``` typescript\n\nvar email = \u003cstring & AsEmail> 'aleksey.bykov@yahoo.com';\nvar firstName = \u003cstring & AsFirstName> 'Aleksey';\nfirstName = email; // \u003c-- compile error\n```\n- `number & In\u003cMhz>`, `number & In\u003cPx>`:\n\n``` typescript\n\nvar freq = \u003cnumber & In\u003cMhz>> 12000;\nvar width = \u003cnumber & In\u003cPx>> 768;\nfreq = width; // \u003c-- compile error\n\nfunction divide\u003ca, b>(left: number & In\u003ca>, right: number & In\u003cb> & AsNonZero) : number & In\u003cRatio\u003ca, b>> {\n return \u003cnumber & In\u003cRatio\u003ca, b>>> left / right;\n}\n\nvar ratio = divide(freq, width); // \u003c-- number & In\u003cRatio\u003cMhz, Px>>\n\n```\n\n```\n```\n","author":{"url":"https://github.com/zpdDG4gta8XKpMCd","@type":"Person","name":"zpdDG4gta8XKpMCd"},"datePublished":"2015-09-21T09:47:25Z","url":"https://github.com/microsoft/TypeScript/issues/4895"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:6944dc36-ab77-c8ae-2fc8-02a6b56a8f34 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E414:2DBD56:12A586:19782D:6AFBFB94 |
| html-safe-nonce | 2234a4b347dd24abbcca983cb824101b46f46b33401d7c9cbb71e27996e2c6e5 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNDE0OjJEQkQ1NjoxMkE1ODY6MTk3ODJEOjZBRkJGQjk0IiwidmlzaXRvcl9pZCI6IjM2NjU2Mjc4MTg2NzYxOTAxMDAiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 9abe30a2baeee354282fa062706c10628dc1cb355b1e1425da8c1f586ef4012e |
| hovercard-subject-tag | issue:107477907 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/4895/issue_layout |
| twitter:image | https://opengraph.githubassets.com/239d8c5ba858689216895a9931ce3009af0ba50a8da3a863ea9f901403672331/microsoft/TypeScript/issues/4895 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/239d8c5ba858689216895a9931ce3009af0ba50a8da3a863ea9f901403672331/microsoft/TypeScript/issues/4895 |
| og:image:alt | Problem There is no straight way to encode a predicate (some checking) about a value in its type. Details There are situations when a value has to pass some sort of check/validation prior to being ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | zpdDG4gta8XKpMCd |
| hostname | github.com |
| expected-hostname | github.com |
| None | fa74413a1d84dac536fcca0740780bcbd3207bafec0e51873b73ff8e8cca032f |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | b3b5633a74535d9c23385512d534c66c8fde1907 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width