Title: Feature Request/Question: Lift the explicit type requirement in assertions for participation in CFA · Issue #45385 · microsoft/TypeScript · GitHub
Open Graph Title: Feature Request/Question: Lift the explicit type requirement in assertions for participation in CFA · Issue #45385 · microsoft/TypeScript
X Title: Feature Request/Question: Lift the explicit type requirement in assertions for participation in CFA · Issue #45385 · microsoft/TypeScript
Description: Suggestion 🔍 Search Terms explicit type, assertion, CFA ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior of existing JavaScript code This could be i...
Open Graph Description: Suggestion 🔍 Search Terms explicit type, assertion, CFA ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior of ...
X Description: Suggestion 🔍 Search Terms explicit type, assertion, CFA ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime beha...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/45385
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Feature Request/Question: Lift the explicit type requirement in assertions for participation in CFA","articleBody":"# Suggestion\r\n\r\n## 🔍 Search Terms\r\n\r\nexplicit type, assertion, CFA\r\n\r\n## ✅ Viability Checklist\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, new syntax sugar for JS, 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\r\n## ⭐ Suggestion\r\n\r\nAs stated in #32695, functions using `asserts` require explicitly typed/annotated like so:\r\n\r\n```ts\r\ndeclare let x: unknown;\r\nconst aFoo = a.literal(\"foo\");\r\naFoo(x); // error\r\n// Assertions require every name in the call target to be declared with an explicit type annotation.(2775)\r\n// input.ts(2, 7): 'aFoo' needs an explicit type annotation.\r\n\r\nconst _aBar = a.literal(\"bar\")\r\nconst aBar: typeof _aBar = _aBar;\r\naBar(x); // works\r\nlet test1: \"bar\" = x\r\n\r\ndeclare let y: unknown;\r\na.string(y) // works\r\nlet test2: string = y;\r\n\r\nnamespace a {\r\n export function literal\u003cT>(t: InferLiteral\u003cT>){\r\n return function(v: unknown): asserts v is T {\r\n if (v !== t) throw new Error()\r\n }\r\n }\r\n\r\n export function string(v: unknown): asserts v is string {\r\n if (typeof v !== \"string\") throw new Error();\r\n }\r\n}\r\ntype InferLiteral\u003cT> =\r\n | (T extends string ? T : string)\r\n | (T extends number ? T : number)\r\n | (T extends boolean ? T : boolean)\r\n```\r\n\r\nThe reason stated in the PR is \"This particular rule exists so that control flow analysis of potential assertion calls doesn't circularly trigger further analysis.\"\r\n\r\nMy question is, umm, what does this mean in more layman terms? My impression was it's to not allow recursive usage but looks like that's not the case because this compiles... So not sure what the above statement means\r\n\r\n```diff\r\n namespace a {\r\n export function literal\u003cT>(t: InferLiteral\u003cT>){\r\n return function(v: unknown): asserts v is T {\r\n+ let _aLol = a.literal(\"lol\")\r\n+ let aLol: typeof _aLol = _aLol;\r\n+ let x = {} as unknown;\r\n+ aLol(x)\r\n+ let test: \"lol\" = x;\r\n if (v !== t) throw new Error()\r\n }\r\n }\r\n```\r\n\r\nAlso I understand it's a \"design limitation\" but, excuse my ignorance, is it really that hard to lift it? Because it's quite annoying to make make two variables for the same function then annotated the other, makes me think \"Eh why can't the compiler do this for itself\" haha. Maybe lift the restriction in some scenarios?\r\n\r\n## 📃 Motivating Example\r\n\r\n## 💻 Use Cases\r\n\r\nI was writing a fail-fast parser that basically composes assertion functions something like this... But I have to use the mentioned workaround. Even if this is too much of a feature request, an explanation why the requirement exists would make me feel less annoyed when I redeclare and annotate assertions :P\r\n\r\n[Playground][1] (Hit on run to see the `ParseError` with message `\"At Person.age: Expected a number\"`)\r\n```ts\r\nnamespace a {\r\n export const string: Asserter\u003cstring> =\r\n (v, p) => invariant(typeof v === \"string\", \"Expected a string\", v, p)\r\n\r\n export const number: Asserter\u003cnumber> =\r\n (v, p) => invariant(typeof v === \"number\", \"Expected a number\", v, p)\r\n \r\n export const object =\r\n \u003cO extends { [_ in string]: Asserter }>(tO: O):\r\n Asserter\u003c{ [K in keyof O]: O[K] extends Asserter\u003cinfer T> ? T : never }> =>\r\n (v, p) => {\r\n invariant((v): v is object => typeof v === \"object\", \"Expected an object\", v, p);\r\n for (let k in tO) {\r\n (tO[k] as any)((v as any)[k], `${p}.${k}`)\r\n }\r\n }\r\n \r\n export class ParseError extends Error {\r\n constructor(message: string, public actual: unknown, public path: string) {\r\n super(`At ${path}: ${message}`)\r\n }\r\n }\r\n\r\n function invariant(test: boolean, message: string, actual: unknown, path: string): void\r\n function invariant\u003cT, U extends T>(test: (v: T) => v is U, message: string, actual: T, path: string): asserts actual is U\r\n function invariant\u003cT>(test: (v: T) => boolean, message: string, actual: T, path: string): void\r\n function invariant(test: boolean | ((v: unknown) => boolean), message: string, actual: unknown, path: string) {\r\n if (typeof test === \"function\" ? !test(actual) : !test)\r\n throw new ParseError(message, actual, path);\r\n }\r\n}\r\ntype Asserter\u003cT = unknown> = (v: unknown, path: string) => asserts v is T\r\n\r\n\r\nconst _aPerson = a.object({ name: a.string, age: a.number })\r\nconst aPerson: typeof _aPerson = _aPerson;\r\n\r\nlet person = { name: \"Devansh\", age: true } as unknown;\r\naPerson(person, \"Person\");\r\nlet test: string = person.name\r\n```\r\n\r\n[1]: https://www.typescriptlang.org/play?jsx=0#code/HYQwtgpgzgDiDGEAEIkG8BQSkQB4wHsAnAFyXgOCjOqIEtgBzALiQEEooJTuAeWhowB8SALxZsSABQA3ADRIYASjEiGMkPRDASUkgE8YEAgDMkMsaNFIARAKY2FNgKL4I8EhAAmKJPcaO5grKGBJ4hKTklNRIwACuYABG3KwcXDxEvPFJ3CLiktLyiiqiasAaWjp6hsZmFlbWNtnJRIEubh7evs3cgUUh2GH4xGQUVGQEiQBW7mT5krwA8ji4nsBeUOhIANoA+kgMfiT0TAC6qZzcnkRIAL5Ceousi0rMEgVpV3xoOwDSB8AkABrCD6UxIRbnCHbX6nFZrDbsS4ZXgMEzcJAAFREAH4sUhWMAIDIMfdVO8CoVgiURJhKZT1Jo6NpdLJXuYDptJjMPKokAYjOD6lZbNzZm1XEZOj5tEgxR4+tSANwU+kmYjSAA2EDIQIB-Je6FV9OkJEW2yBcJAm20+iUUlkKBtwDtFtOCgABgASNAwW4AOh9QNuHqUxoKt3DdwkQwio011s2AAVNFxnEQiBq8AjNunMzc6ZIxrQ4h5iFJIJwQIwIKx-ME4olNXR4CgPHEQJrWHFgEDgAQAO7ABtNluKEAkAAWdeOghUhYKUDiRiIUg9bDIPrgU9urB9lag1YgIbDEYkkYkJh7HjolABFWZVU81FYiQIBG12gUB6PM5OjAUBASA7LskB7PtB2Hccpz-OdWBkAg6C8S9rxIW9AUZSoSF4TEFAAVXhCB1k2bE9GgEhWFkVhMRpDk6E2PDv2gQ8a1gphAPbTtqOCCdpyOf92UTK4bU4zVOSQPCUOAG870wx9sNI58KMKajaLfD8IC-JAf1Y-jBA44CuKxHiYL0ph2QQpCpJkjDyiZFkyJfJB1M-QEAB9pCosDe37Ic1PfVylCYqtdPrNtDNA8DfKg7c+P8ecKToMxqkFMwlMsRor2ktDKBsJA8QAQiUqQgJAlRWCK8jT0pKdMwHWIIHqlMiDTDNyx0iADJAkzJyUFVsEjSMBWQT4UUxMRvIgoc8hUybop6tjGFooTSE2Cx6KxUIMGLMhdhAJNuCgO9rBAf15V0H5QEgVhTrC38UH9HobluMMdpQA6WsoVhhvBPaPqOwFrD+w7KBVDBtTIFcAYmy7wFrWwABFiW0KBJ0Ce7jjiZBbidObIJVfaQeAKQocoJx-tyvrwZ1flyMWibSeAR64YwIA","author":{"url":"https://github.com/devanshj","@type":"Person","name":"devanshj"},"datePublished":"2021-08-09T22:48:29Z","url":"https://github.com/microsoft/TypeScript/issues/45385"}
| 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:084e6c95-a1b4-dd6a-815f-b39243ac8f58 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | AEF6:1C94F:12D743:1837C6:6B00F975 |
| html-safe-nonce | aaa84102d033a262184aa577fe47ef236f7f2d01b8019bf730aeb5bee6fa6c10 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBRUY2OjFDOTRGOjEyRDc0MzoxODM3QzY6NkIwMEY5NzUiLCJ2aXNpdG9yX2lkIjoiNjM3ODQ5NTkzNjQxMDIyMDkxNyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | c3bfcd709190a0c65199f5a7d8025424754ca226d5dfacf81213f0e230d2d600 |
| hovercard-subject-tag | issue:964448303 |
| 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/45385/issue_layout |
| twitter:image | https://opengraph.githubassets.com/9173386fb2851819cbc74d998193ac3faf4ab2108ec418b929c92f152cb77a7e/microsoft/TypeScript/issues/45385 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/9173386fb2851819cbc74d998193ac3faf4ab2108ec418b929c92f152cb77a7e/microsoft/TypeScript/issues/45385 |
| og:image:alt | Suggestion 🔍 Search Terms explicit type, assertion, CFA ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior of ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | devanshj |
| hostname | github.com |
| expected-hostname | github.com |
| None | e208d86428ec00a57ade75058166297440e8128a01e5287c31a53dc042bbf187 |
| 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 | 7dafd017fb7809a839c443dba08622af38e63c09 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width