René's URL Explorer Experiment


Title: `as enum` assertion for object literals · Issue #60790 · microsoft/TypeScript · GitHub

Open Graph Title: `as enum` assertion for object literals · Issue #60790 · microsoft/TypeScript

X Title: `as enum` assertion for object literals · Issue #60790 · microsoft/TypeScript

Description: 🔍 Search Terms enum, object literal, type-stripping ✅ 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 imple...

Open Graph Description: 🔍 Search Terms enum, object literal, type-stripping ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior of exis...

X Description: 🔍 Search Terms enum, object literal, type-stripping ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior...

Opengraph URL: https://github.com/microsoft/TypeScript/issues/60790

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`as enum` assertion for object literals","articleBody":"### 🔍 Search Terms\n\nenum, object literal, type-stripping\n\n### ✅ Viability Checklist\n\n- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code\n- [x] This wouldn't change the runtime behavior of existing JavaScript code\n- [x] This could be implemented without emitting different JS based on the types of the expressions\n- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)\n- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types\n- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals\n\n### Context\n\nWhile TypeScript already allows declaring runtime enums values:\n\n```ts\nexport enum Compass {\n  N = \"N\",\n  S = \"S\",\n  E = \"E\",\n  W = \"W\",\n}\n```\n\nThis is not standard JavaScript, and does not work in Node.js unless [`--experimental-transform-types`](https://nodejs.org/api/cli.html#--experimental-transform-types) is passed.\n\nAn alternative \"pure JS\" pattern from the TypeScript handbook is:\n\n```ts\nexport const Compass = {\n  N: \"N\",\n  S: \"S\",\n  E: \"E\",\n  W: \"W\",\n} as const;\nexport type Compass = typeof Compass[keyof typeof Compass];\n```\n\nhttps://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums\n\nThere are two downsides to this pattern:\n\n- `typeof X[keyof typeof X]` is both verbose and not beginner friendly.\n- The type aliases are not nominal, they are a _plain_ union type.\n\n### ⭐ Suggestion\n\nIntroduce some new syntax to TypeScript to help with the object-literal-as-enum pattern.\n\nFor example would be allowing `as enum`:\n\n```ts\nexport const Compass = {\n  N: \"N\",\n  S: \"S\",\n  E: \"E\",\n  W: \"W\",\n} as enum;\n```\n\n(from #59658)\n\nAn alternative design could be allowing an `enum` type annotation on `const` variable declarations `export const Compass: enum = {...}`.\n\nThis annotation would effectively be the same as writing:\n\n```ts\n/** secret internal type - here to get nominal typing */\ndeclare const enum __Compass__ {\n    N = \"N\",\n    S = \"S\",\n    E = \"E\",\n    W = \"W\",\n}\nexport const Compass = {\n  N: \"N\" as __Compass__.N,\n  S: \"S\" as __Compass__.S,\n  E: \"E\" as __Compass__.E,\n  W: \"W\" as __Compass__.W,\n} as const;\nexport type Compass = __Compass__;\n```\n\n### Rules\n\nThe `enum` annotation would only be permitted for object literals that are\n - in a declarative position\n - have compile-time constant key+values\n - all values are either strings, numbers, or references to constant strings/numbers.\n\ni.e. the object literal would follow very similar rules that are applied to `const enum C {}` syntax\n\n```ts\n// @ts-expect-error\nfoo({ a: \"a\" } as enum);\n\nclass C {\n   // @ts-expect-error\n   f: enum = {}\n}\n\nconst o = {\n   // @ts-expect-error\n   p: Math.random()\n} as enum;\n```\n\n### Benefits\n\n- The standard JS of an object lieral with the type-checking of an `enum`\n- An explicit marker for tools such as linters to provide extra checks (e.g. enum naming conventions)\n\n### Downsides\n\nWhile this object literal as enum pattern is popular in codebases that avoid non-standard runtime syntax it does not have all the features available with `enum` syntax such as self-reference during construction.\n\n`__proto__: null` is currently not supported #38385 making it difficult to avoid object literals from inheriting non-enum properties resulting in false positives with `key in MyEnum`.\n\n\n### 📃 Motivating Example\n\n```ts\nexport const Compass = {\n  N: \"N\",\n  S: \"S\",\n  E: \"E\",\n  W: \"W\",\n} as enum;\nObject.freeze(Compass);\n\nexport function reverse(c: Compass): Compass {\n   if (c === Compass.N) return Compass.S;\n   if (c === Compass.S) return Compass.N;\n   if (c === Compass.E) return Compass.W;\n   if (c === Compass.W) return Compass.E;\n   throw new Error(\"unreachable code was run\");\n}\n```\n\nThe above module will work out-of-the-box in Node.js (assuming  https://github.com/nodejs/typescript/issues/17).\n\n\n### 💻 Use Cases\n\n1. What do you want to use this for?\n\nCreating an enum like value using standard Object literal syntax with some of the type system benefits that `enum` syntax has.\n\n2. What shortcomings exist with current approaches?\n\n- `typeof Foo[keyof typeof Foo]` is not beginner friendly and is not a nominal type\n\n3. What workarounds are you using in the meantime?\n\nOne workaround is to have a small utility for emulating an enum like nominal type from an object literal ([playground](https://www.typescriptlang.org/play/?ts=5.7.2#code/FAEwpgxgNghgTmABBA9gOwM4BdEFE0CuAtgMoCeRAXIgWgJYCOBSGFARilANzBZkAOSfMQBicFEQA8AFURgAHljBoQGRAG8AvgD5EAXkSyFSlWvWIA2v3H9q2OHTQBzALrVHAMzBw8iTYgB+X2o0MAA3bx5gD1oILDp0PEIpVEwcI0VlVUQAJUgUOBBJe0cnABpEEudEAB9EZLZvbW0ACgxBCGppAEpqcwQYEHQoMksAa0RHRDGwMhQPQzdDCzGXRAAyDUthUgolmbmF6X9-dWBEC8QELAI4NEqOxBg1GDQyHk1gYAV+ApxU7CIADCEn4zzUBh2LTOFwActQAESwhEVEiIkgovCI3CYgDqiNxCOAmm6PB+f0QfEEwNB4P0SVE4ikVLA8xpRDBGAw2h4QA)). The `\"literal\" \u0026 { __key__: val }` trick _works_ but results in _noisey_ types when displayed to the developer (e.g. in an error message)\n","author":{"url":"https://github.com/acutmore","@type":"Person","name":"acutmore"},"datePublished":"2024-12-17T16:29:54.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":8},"url":"https://github.com/60790/TypeScript/issues/60790"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:6cd9c60c-9d9a-b623-97e5-d2d24187d5a1
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idEB14:34AAF2:59051B:79A063:6A4D4049
html-safe-nonce28ac3140f0cd69edaef29c6f95fd83e1c569665588e5b0f965512b4e0027981f
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFQjE0OjM0QUFGMjo1OTA1MUI6NzlBMDYzOjZBNEQ0MDQ5IiwidmlzaXRvcl9pZCI6IjE1ODA0Njg5NTIxOTgxMDMxMTQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac94441364d64c190296565542736a2e78b313ac66c7705a298255dccbf985f66a
hovercard-subject-tagissue:2745418842
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/60790/issue_layout
twitter:imagehttps://opengraph.githubassets.com/7949e535ccc4a992b4d9bcbf4b4dc843373b5273685a5e61c05fd18fac0f83e2/microsoft/TypeScript/issues/60790
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/7949e535ccc4a992b4d9bcbf4b4dc843373b5273685a5e61c05fd18fac0f83e2/microsoft/TypeScript/issues/60790
og:image:alt🔍 Search Terms enum, object literal, type-stripping ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior of exis...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameacutmore
hostnamegithub.com
expected-hostnamegithub.com
None92571a8944142227b7e19cd10918b1ddd06e5066c1ad5bc7e4769cf6140a87e6
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
release56fc8347865a14e2ec811533d68f929cf4e0ec19
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/microsoft/TypeScript/issues/60790#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F60790
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
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
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://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/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F60790
Sign up https://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/60790
Reloadhttps://github.com/microsoft/TypeScript/issues/60790
Reloadhttps://github.com/microsoft/TypeScript/issues/60790
Please reload this pagehttps://github.com/microsoft/TypeScript/issues/60790
microsoft https://github.com/microsoft
TypeScripthttps://github.com/microsoft/TypeScript
Notifications https://github.com/login?return_to=%2Fmicrosoft%2FTypeScript
Fork 13.5k https://github.com/login?return_to=%2Fmicrosoft%2FTypeScript
Star 109k https://github.com/login?return_to=%2Fmicrosoft%2FTypeScript
Code https://github.com/microsoft/TypeScript
Issues 5k+ https://github.com/microsoft/TypeScript/issues
Pull requests 32 https://github.com/microsoft/TypeScript/pulls
Actions https://github.com/microsoft/TypeScript/actions
Projects https://github.com/microsoft/TypeScript/projects
Models https://github.com/microsoft/TypeScript/models
Wiki https://github.com/microsoft/TypeScript/wiki
Security and quality 0 https://github.com/microsoft/TypeScript/security
Insights https://github.com/microsoft/TypeScript/pulse
Code https://github.com/microsoft/TypeScript
Issues https://github.com/microsoft/TypeScript/issues
Pull requests https://github.com/microsoft/TypeScript/pulls
Actions https://github.com/microsoft/TypeScript/actions
Projects https://github.com/microsoft/TypeScript/projects
Models https://github.com/microsoft/TypeScript/models
Wiki https://github.com/microsoft/TypeScript/wiki
Security and quality https://github.com/microsoft/TypeScript/security
Insights https://github.com/microsoft/TypeScript/pulse
as enum assertion for object literalshttps://github.com/microsoft/TypeScript/issues/60790#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/acutmore
acutmorehttps://github.com/acutmore
on Dec 17, 2024https://github.com/microsoft/TypeScript/issues/60790#issue-2745418842
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
--experimental-transform-typeshttps://nodejs.org/api/cli.html#--experimental-transform-types
https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enumshttps://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums
#59658https://github.com/microsoft/TypeScript/issues/59658
#38385https://github.com/microsoft/TypeScript/issues/38385
nodejs/typescript#17https://github.com/nodejs/typescript/issues/17
playgroundhttps://www.typescriptlang.org/play/?ts=5.7.2#code/FAEwpgxgNghgTmABBA9gOwM4BdEFE0CuAtgMoCeRAXIgWgJYCOBSGFARilANzBZkAOSfMQBicFEQA8AFURgAHljBoQGRAG8AvgD5EAXkSyFSlWvWIA2v3H9q2OHTQBzALrVHAMzBw8iTYgB+X2o0MAA3bx5gD1oILDp0PEIpVEwcI0VlVUQAJUgUOBBJe0cnABpEEudEAB9EZLZvbW0ACgxBCGppAEpqcwQYEHQoMksAa0RHRDGwMhQPQzdDCzGXRAAyDUthUgolmbmF6X9-dWBEC8QELAI4NEqOxBg1GDQyHk1gYAV+ApxU7CIADCEn4zzUBh2LTOFwActQAESwhEVEiIkgovCI3CYgDqiNxCOAmm6PB+f0QfEEwNB4P0SVE4ikVLA8xpRDBGAw2h4QA
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.