Title: Feature Request: Custom errors via type param utility when used as a default · Issue #41392 · microsoft/TypeScript · GitHub
Open Graph Title: Feature Request: Custom errors via type param utility when used as a default · Issue #41392 · microsoft/TypeScript
X Title: Feature Request: Custom errors via type param utility when used as a default · Issue #41392 · microsoft/TypeScript
Description: Search Terms Throw, error, in, type, param, custom, message, assert The Problem The ability to signal sources of error is critical to the productivity of both library developers and consumers; without this ability, it's easy to get lost ...
Open Graph Description: Search Terms Throw, error, in, type, param, custom, message, assert The Problem The ability to signal sources of error is critical to the productivity of both library developers and consumers; with...
X Description: Search Terms Throw, error, in, type, param, custom, message, assert The Problem The ability to signal sources of error is critical to the productivity of both library developers and consumers; with...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/41392
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Feature Request: Custom errors via type param utility when used as a default","articleBody":"## Search Terms\r\n\r\nThrow, error, in, type, param, custom, message, assert\r\n\r\n## The Problem\r\n\r\nThe ability to signal sources of error is critical to the productivity of both library developers and consumers; without this ability, it's easy to get lost in a sea of difficult-to-trace `never`s.\r\n\r\nPR #40468 is incredibly exciting. However, it's unclear how users could specify the positioning and bubbling of error messages. This issue details a different approach, one using a would-be intrinsic `ParamError` utility type, which would be used in lieu of type variable defaults.\r\n\r\n## Suggestion\r\n\r\n```ts\r\ntype IsValid\u003cT> = // ... the predicate type\r\n\r\ntype WithComplexConstraint\u003c\r\n InQuestion, // \u003c-- the type in need of validation\r\n DidThrow = ParamError\u003c\"That's invalid!\", InQuestion, IsValid\u003cInQuestion> ? false : true>\r\n // ^ ^ ^\r\n // | | |\r\n // | | 3. A boolean representing whether or not to error)\r\n // | 2. The type param over which to display the error\r\n // 1. The error message\r\n> = // ...\r\n```\r\n\r\nIn the use case below, I describe a generic `IsEmailAddress` predicate type, and an `acceptsEmailAddress` function, which constrains the first param according to the `IsEmailAddress` predicate. Here's how such validation would look using `ParamError`:\r\n\r\n```ts\r\ntype IsEmailAddress\u003cS extends string> = // ...\r\n\r\ndeclare function acceptsEmailAddress\u003c\r\n S extends string,\r\n IsInvalid = ParamError\u003c\"The supplied string type is not an email address type.\", S, IsEmailAddress\u003cS>>\r\n>(emailAddress: S): void;\r\n\r\nacceptsEmailAddress(\"rickross@smoothrapping.com\");\r\nacceptsEmailAddress(\"toppotdoughnuts.com\");\r\n// ~~~~~~~~~~~~~~~~~~~~\r\n// ^\r\n// type-error: \"The supplied string type is not an email address type.\"\r\n```\r\n\r\nOne could have multiple validations target the same type param:\r\n\r\n```ts\r\ntype IsEmailAddress\u003cS extends string> = // ...\r\ntype IsHotmailDotCom\u003cS extends string> = S extends `${infer Local}@hotmail.com` ? true : false;\r\n\r\ndeclare function acceptsEmailAddress\u003c\r\n S extends string,\r\n IsInvalid = ParamError\u003c\"The supplied string type is not an email address type.\", S, IsEmailAddress\u003cS>>,\r\n IsHotmail = ParamError\u003c\"I respect it, but cummon... hotmail... in 2020? You still playing Neopets too?\", S, IsHotmailDotCom\u003cS>>\r\n>(emailAddress: S): void;\r\n\r\nacceptsEmailAddress(\"rickyrose@hotmail.com\");\r\n// ~~~~~~~~~~~~~~~~~~~~~~\r\n// ^\r\n// type-error: \"The supplied string type is not an email address type.\"\r\n// type-error: \"I respect it, but cummon... hotmail... in 2020? You still playing Neopets too?\"\r\n```\r\n\r\n## Use Case\r\n\r\nWhile the key use case is enabling library developers to create simpler error messaging experiences (and put aside the practice of `never`-hunting), you may have noticed another critical use case: **constraining params by more than just subtype**. Thanks to conditional and recursive types, we can traverse large structures and make judgements predicated upon more than could be represented with a subtype check.\r\n\r\nLet's say we want to validate that a string literal is an email address. We begin by building the `IsEmail` predicate and its children.\r\n\r\n```ts\r\ntype IsValidLocal\u003cS> extends string = // ...\r\ntype IsValidDomain\u003cS extends string> = // ...\r\ntype IsValidExtension\u003cS extends string> = // ...\r\n\r\ntype AllTrue\u003cT extends boolean[]> = // ...\r\n\r\ntype IsEmail\u003cS extends string> = S extends `${infer Local}@${infer Domain}.${infer Extension}`\r\n ? AllTrue\u003c[IsValidLocal\u003cLocal>, IsValidDomain\u003cDomain>, IsValidExtension\u003cExtension>]>\r\n : false;\r\n```\r\n\r\nThis is not a type that we can represent today as a generic constraint. Aka, we are unable to do the following:\r\n\r\n```ts\r\ntype EmailAddress = // ... somehow with the constraints defined above\r\n\r\ndeclare function acceptsEmailAddress(emailAddress: EmailAddress): void;\r\n```\r\n\r\nWhile I hope that [conditional assignability](https://github.com/microsoft/TypeScript/issues/40779) soon solves this problem, we're currently stuck. The only solutions seem to be:\r\n\r\n1. Leave the validation dangling beneath the function's usage (difficult to maintain / enforce).\r\n\r\n```ts\r\ndeclare function acceptsEmailAddress(emailAddress: string): void;\r\n\r\nconst emailAddress = \"rick@ross.com\";\r\nacceptsEmailAddress(emailAddress);\r\n\r\ntype EmailAddress = typeof emailAddress;\r\ntype UsedCorrectly = IsEmailAddress\u003cEmailAddress>;\r\nassert\u003cIsExact\u003cUsedCorrectly, true>>(true); // using `conditional-type-checks`\r\n```\r\n\r\n2. Produce an error-indicating return signature and check for that signature where `acceptsEmailAddress`'s output is referenced (also difficult to maintain / enforce).\r\n\r\n```ts\r\ntype Error\u003cMessage extends string> = {error: Message};\r\n\r\ndeclare function acceptsEmailAddress\u003cE extends string>(emailAddress: E): IsEmailAddress\u003cE> extends true ? Error\u003c\"Invalid email address supplied\"> : string;\r\n\r\nconst emailAddress = \"rick@ross.com\";\r\nconst result = acceptsEmailAddress(emailAddress);\r\n\r\ndeclare function acceptsResult(result: string): void;\r\n\r\nacceptsResult(result); // throws a type error if `emailAddress`'s type does not pass the `IsEmail` check\r\n```\r\n\r\n## Checklist\r\n\r\nMy suggestion meets these guidelines:\r\n\r\n* [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code\r\n* [x] This wouldn't change the runtime behavior of existing JavaScript code\r\n* [x] This could be implemented without emitting different JS based on the types of the expressions\r\n* [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)\r\n* [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).\r\n","author":{"url":"https://github.com/harrysolovay","@type":"Person","name":"harrysolovay"},"datePublished":"2020-11-04T00:03:42Z","url":"https://github.com/microsoft/TypeScript/issues/41392"}
| 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:1dfc15bc-c7ae-a2ff-8937-8f02eb5495ff |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DBFA:A71F9:1A3DFE7:2119C8A:6B0186BE |
| html-safe-nonce | f3a45397d29a2cb64ed3ab857afbc499c06cb28251016af5f8cd895b1c93fac5 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQkZBOkE3MUY5OjFBM0RGRTc6MjExOUM4QTo2QjAxODZCRSIsInZpc2l0b3JfaWQiOiI4MjU0MTQwOTgxMDA4NTAwNDE0IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | f3c7596b8e6a4d64d5501a85c0414ccd548512b11e64fb05b72d97283d7be7d4 |
| hovercard-subject-tag | issue:735714891 |
| 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/41392/issue_layout |
| twitter:image | https://opengraph.githubassets.com/e9d3dea19b10eed9dab1a293235d7ed6ddb1617c7687d21e4f34bae64d153dc4/microsoft/TypeScript/issues/41392 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/e9d3dea19b10eed9dab1a293235d7ed6ddb1617c7687d21e4f34bae64d153dc4/microsoft/TypeScript/issues/41392 |
| og:image:alt | Search Terms Throw, error, in, type, param, custom, message, assert The Problem The ability to signal sources of error is critical to the productivity of both library developers and consumers; with... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | harrysolovay |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| 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 | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width