Title: C++-style `const` modifier on class members · Issue #58236 · microsoft/TypeScript · GitHub
Open Graph Title: C++-style `const` modifier on class members · Issue #58236 · microsoft/TypeScript
X Title: C++-style `const` modifier on class members · Issue #58236 · microsoft/TypeScript
Description: 🔍 Search Terms const method parameter keyword readonly class C++ like const methods class method with const keyword "as const" for class type ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code...
Open Graph Description: 🔍 Search Terms const method parameter keyword readonly class C++ like const methods class method with const keyword "as const" for class type ✅ Viability Checklist This wouldn't be a breaking chang...
X Description: 🔍 Search Terms const method parameter keyword readonly class C++ like const methods class method with const keyword "as const" for class type ✅ Viability Checklist This wouldn't be a ...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/58236
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"C++-style `const` modifier on class members","articleBody":"### 🔍 Search Terms\r\n\r\nconst method parameter keyword readonly class\r\nC++ like const methods\r\nclass method with const keyword\r\n\"as const\" for class type\r\n\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 isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types\r\n- [X] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals\r\n\r\n### ⭐ Suggestion\r\n\r\n~~I'm sure I've seen this suggestion somewhere before but I couldn't find it~~ https://github.com/microsoft/TypeScript/issues/35313\r\n\r\nAllow using `as const` on class objects by annotating methods as `const` (syntax tbd).\r\n\r\nA const method would (like in C++) not allow modifying properties of `this` or calling any method not also marked as `const`.\r\n\r\nAn object marked with `as const` would similarly be readonly and only methods marked as `const` would be callable.\r\n\r\n### 📃 Motivating Example\r\n\r\nKeeping track of mutable vs immutable can be tricky when you're not used to the library you're using (or if its poorly written). It's very important to get it right in many libraries (`react` state, `vue` refs (shallow vs deep), `preact/signals`) where modifying values may or may not be required.\r\n\r\nDebugging mutability bugs can be a pain sometimes too\r\n\r\n```ts\r\nconst start = new Point(0, 0);\r\nconst line: Point[] = [];\r\n\r\nfor (let i = 0; i \u003c 10; i++) {\r\n line.push(start.add(i * 10, Math.random()));\r\n}\r\n\r\n// equivalent to\r\nconst line = new Array(10).fill(new Point(450, Math.random()));\r\n```\r\n\r\n### Declaration syntax 1 using a `const` decoration\r\n\r\n```ts\r\nclass Point {\r\n\tconstructor(public x: number, public y: number) { }\r\n\tconst clone(): Point { ... }\r\n\r\n\tadd(other: PointLike): this { ... }\r\n}\r\n\r\nconst p = new Point(0, 0) as const; // type is { readonly x: number, readonly y: number, readonly clone(): Point } (`add` has been removed)\r\n```\r\n\r\n### Declaration syntax 2 using `this: const` parameter\r\n\r\n```ts\r\nclass Point {\r\n\tconstructor(public x: number, public y: number) { }\r\n\tclone(this: const): Point { ... }\r\n\r\n\tadd(other: PointLike): this { ... }\r\n}\r\n\r\nconst p = new Point(0, 0) as const; // type is { readonly x: number, readonly y: number, readonly clone(): Point } (`add` has been removed)\r\n```\r\n\r\nI personally much prefer the first syntax where `const` is a decoration.\r\n\r\n### Parameter syntax 1\r\n\r\n```ts\r\nfunction noModifyPoint(p: const Point) {\r\n\tp.clone().add(1, 1);\r\n}\r\n\r\nfunction modifyPoint(p: Point) {\r\n\tp.add(1, 1);\r\n}\r\n\r\nconst p = new Point(0, 0) as const;\r\n\r\nnoModifyPoint(p); // ok\r\nmodifyPoint(p); // Argument of type `const Point` is not assignable to parameter of type `Point`. Type `const Point` is missing the following properties from type `Point`: add\r\n```\r\n\r\nNot to be confused with\r\n\r\n```ts\r\nfunction foo() {\r\n\tconst p = arguments[0];\r\n\t//...\r\n}\r\n```\r\n\r\n(as an aside a more appropriate syntax for that would be `foo(const p: Point)` or `foo(const p: const Point)` but that's OoS)\r\n\r\n### Parameter syntax 2\r\n\r\n```ts\r\nfunction noModifyPoint(p: Readonly\u003cPoint>) {\r\n\tp.clone().add(1, 1);\r\n}\r\n\r\nfunction modifyPoint(p: Point) {\r\n\tp.add(1, 1);\r\n}\r\n\r\nconst p = new Point(0, 0) as const;\r\n\r\nnoModifyPoint(p); // ok\r\nmodifyPoint(p); // Argument of type `Readonly\u003cPoint>` is not assignable to parameter of type `Point`. Type `Readonly\u003cPoint>` is missing the following properties from type `Point`: add\r\n```\r\n\r\nAgain I prefer syntax 1. The const type inference needs to happen in the compiler, making it look like a utility type would be confusing. The use of `const` also mirrors the declaration syntax 1.\r\n\r\nThe inference of the new readonly type should :tm: be simple enough, convert any r/w properties to readonly, and remove any functions not marked as const.\r\n\r\nFor simplicity arrow method properties should be handled as any other property would.\r\n\r\n```ts\r\nclass Point {\r\n\tconstructor(public x: number, public y: number) { }\r\n\tclone(this: const): Point { ... }\r\n\r\n\tunsafelyModifyThis: () => { this.x = 10; }\r\n}\r\n\r\nconst p = new Point(0, 0) as const;\r\n\r\np.unsafelyModifyThis(); // OK\r\n```\r\n\r\nThe reason I suggest this is only because there needs to be a line drawn somewhere as to how complex this feature becomes. As mentioned in [TypeScripts third non-goal](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#:~:text=Apply%20a%20sound%20or%20%22provably%20correct%22%20type%20system.%20Instead%2C%20strike%20a%20balance%20between%20correctness%20and%20productivity) this is a tradeoff between usefulness and simplicity.\r\n\r\nIts already possible to break the type system and its up to the programmers to not do stupid things.\r\n\r\n### Other types\r\n\r\n```ts\r\nconst a1 = [1, 2, 3] as const;\r\nconst a2 = [1, 2, 3] as Readonly\u003c[number, number, number]>;\r\n\r\nfunction aFunc1\u003cT>(p: const Array\u003cT>) {\r\n\t// syntactically valid but is probably useful since Array doesn't have any built-in const decorations\r\n\t// the resulting type would be `{ readonly [index: number]: T; readonly length: number }`\r\n\t// also not sure how it would work with the `ReadonlyArray\u003cT>` built-in type\r\n\t...\r\n}\r\n\r\nfunction prim(n: const number) { ... } //error\r\n```\r\n\r\n### 💻 Use Cases\r\n\r\n1. What do you want to use this for?\r\n\tThis would be most useful for data classes (aka structs) that represent non-primative data structures.\r\n2. What shortcomings exist with current approaches?\r\n\tWorkarounds are not DRY, requiring manual definition for const variants of all types\r\n3. What workarounds are you using in the meantime?\r\n\tManually defining a `ReadonlyPoint` variation and casting to it.\r\n\r\n\t```ts\r\n\tinterface ReadonlyPoint {\r\n\t\treadonly x: number;\r\n\t\treadonly y: number;\r\n\t\treadonly xy: [number, number];\r\n\t\r\n\t\tclone(): Point;\r\n\t}\r\n\t\r\n\tclass Point implements ReadonlyPoint {\r\n\t\tconstructor(public x: number, public y: number) { }\r\n\t\r\n\t\tclone(): Point {\r\n\t\t\treturn new Point(this.x, this.y);\r\n\t\t}\r\n\t\r\n\t\tadd(other: PointLike): this {\r\n\t\t\tthis.x += other.x;\r\n\t\t\tthis.y += other.y;\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\r\n\t\t//...\r\n\t}\r\n\t\r\n\tconst p = new Point(0, 0) as ReadonlyPoint;\r\n\t\r\n\tp.add(p); // error\r\n\t```","author":{"url":"https://github.com/OldStarchy","@type":"Person","name":"OldStarchy"},"datePublished":"2024-04-18T04:43:08Z","url":"https://github.com/microsoft/TypeScript/issues/58236"}
| 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:da2991d9-de3a-e08c-cb1c-78e25066bace |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DE42:3D1845:16869C:1F4AEC:6AFBDDFE |
| html-safe-nonce | 85224e35b9b030d0ab05062910f7499f24b0a19dcc87dd3cc7a2431114d351d7 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJERTQyOjNEMTg0NToxNjg2OUM6MUY0QUVDOjZBRkJEREZFIiwidmlzaXRvcl9pZCI6IjYzMTMzNzcyNzg2NTA0NzM5ODIiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | db81cad96d09cce10e71fd40d87db4c263fcca1e607a92630a658fac785ae223 |
| hovercard-subject-tag | issue:2249732311 |
| 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/58236/issue_layout |
| twitter:image | https://opengraph.githubassets.com/07066c569b931c0d4aa5a8bb787883e24686d12bb84e92e921f2ece7f806f4da/microsoft/TypeScript/issues/58236 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/07066c569b931c0d4aa5a8bb787883e24686d12bb84e92e921f2ece7f806f4da/microsoft/TypeScript/issues/58236 |
| og:image:alt | 🔍 Search Terms const method parameter keyword readonly class C++ like const methods class method with const keyword "as const" for class type ✅ Viability Checklist This wouldn't be a breaking chang... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | OldStarchy |
| hostname | github.com |
| expected-hostname | github.com |
| None | 744d4381b1c4dbd6d8736c7d7e5bbe7dc11217584e457a3555020c631764e8ec |
| 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 | df859c48a4c8b4c0009c19bb4e82101aacb4b998 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width