René's URL Explorer Experiment


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

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:da2991d9-de3a-e08c-cb1c-78e25066bace
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idDE42:3D1845:16869C:1F4AEC:6AFBDDFE
html-safe-nonce85224e35b9b030d0ab05062910f7499f24b0a19dcc87dd3cc7a2431114d351d7
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJERTQyOjNEMTg0NToxNjg2OUM6MUY0QUVDOjZBRkJEREZFIiwidmlzaXRvcl9pZCI6IjYzMTMzNzcyNzg2NTA0NzM5ODIiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmacdb81cad96d09cce10e71fd40d87db4c263fcca1e607a92630a658fac785ae223
hovercard-subject-tagissue:2249732311
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/58236/issue_layout
twitter:imagehttps://opengraph.githubassets.com/07066c569b931c0d4aa5a8bb787883e24686d12bb84e92e921f2ece7f806f4da/microsoft/TypeScript/issues/58236
twitter:cardsummary_large_image
og:imagehttps://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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameOldStarchy
hostnamegithub.com
expected-hostnamegithub.com
None744d4381b1c4dbd6d8736c7d7e5bbe7dc11217584e457a3555020c631764e8ec
turbo-cache-controlno-preview
go-importgithub.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git
octolytics-dimension-user_id6154722
octolytics-dimension-user_loginmicrosoft
octolytics-dimension-repository_id20929025
octolytics-dimension-repository_nwomicrosoft/TypeScript
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id20929025
octolytics-dimension-repository_network_root_nwomicrosoft/TypeScript
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasedf859c48a4c8b4c0009c19bb4e82101aacb4b998
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/microsoft/TypeScript/issues/58236#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F58236
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F58236
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=microsoft%2FTypeScript
Reloadhttps://github.com/microsoft/TypeScript/issues/58236
Reloadhttps://github.com/microsoft/TypeScript/issues/58236
Reloadhttps://github.com/microsoft/TypeScript/issues/58236
microsofthttps://github.com/microsoft
TypeScripthttps://github.com/microsoft/TypeScript
Codehttps://github.com/microsoft/TypeScript
Issues5k (5k)https://github.com/microsoft/TypeScript/issues
Pull requests334 (334)https://github.com/microsoft/TypeScript/pulls
Actionshttps://github.com/microsoft/TypeScript/actions
Projectshttps://github.com/microsoft/TypeScript/projects
Wikihttps://github.com/microsoft/TypeScript/wiki
Security and qualityhttps://github.com/microsoft/TypeScript/security
Insightshttps://github.com/microsoft/TypeScript/pulse
https://github.com/microsoft/TypeScript
New issuehttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/58236
New issuehttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/58236
C++-style const modifier on class membershttps://github.com/microsoft/TypeScript/issues/58236#top
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featurehttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Awaiting%20More%20Feedback%22
SuggestionAn idea for TypeScripthttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Suggestion%22
https://github.com/OldStarchy
OldStarchyhttps://github.com/OldStarchy
on Apr 18, 2024https://github.com/microsoft/TypeScript/issues/58236#issue-2249732311
https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Typeshttps://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goalshttps://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
#35313https://github.com/microsoft/TypeScript/issues/35313
TypeScripts third non-goalhttps://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
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
SuggestionAn idea for TypeScripthttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Suggestion%22
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featurehttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Awaiting%20More%20Feedback%22
on Apr 18, 2024https://github.com/microsoft/TypeScript/issues/58236#event-12528265186
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
on Apr 18, 2024https://github.com/microsoft/TypeScript/issues/58236#event-12528266679
https://github.com/RyanCavanaugh
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
on Apr 18, 2024https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2065166982
https://github.com/MartinJohns
Martin Johns (MartinJohns)https://github.com/MartinJohns
on Apr 21, 2024https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2067920320
#35313https://github.com/microsoft/TypeScript/issues/35313
https://github.com/OldStarchy
OldStarchyhttps://github.com/OldStarchy
on Apr 22, 2024https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2068574191
https://github.com/OldStarchy
OldStarchyhttps://github.com/OldStarchy
on Apr 22, 2024https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2068586582
https://github.com/Perfectoff
Perfectoffhttps://github.com/Perfectoff
on May 16, 2025https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2885548252
therehttps://github.com/microsoft/TypeScript/issues/61690
https://github.com/james-pre
James Prevett (james-pre)https://github.com/james-pre
on May 16, 2025https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2887277282
https://github.com/MartinJohns
Martin Johns (MartinJohns)https://github.com/MartinJohns
on May 16, 2025https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2887548863
https://github.com/Perfectoff
Perfectoffhttps://github.com/Perfectoff
on May 16, 2025https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2887688453
https://github.com/Perfectoff
Perfectoffhttps://github.com/Perfectoff
on May 16, 2025https://github.com/microsoft/TypeScript/issues/58236#issuecomment-2887708112
Sign up for freehttps://github.com/signup?return_to=https://github.com/microsoft/TypeScript/issues/58236
Sign in to commenthttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/58236
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featurehttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Awaiting%20More%20Feedback%22
SuggestionAn idea for TypeScripthttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Suggestion%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.