René's URL Explorer Experiment


Title: Confusing aspects of recent improvements to Index Types · Issue #23994 · microsoft/TypeScript · GitHub

Open Graph Title: Confusing aspects of recent improvements to Index Types · Issue #23994 · microsoft/TypeScript

X Title: Confusing aspects of recent improvements to Index Types · Issue #23994 · microsoft/TypeScript

Description: TypeScript Version: HEAD Search Terms: 23592, index number string keyof Code interface OnlyStrings { [key: string]: boolean; } type OnlyStringsKeys = keyof OnlyStrings; // string | number let dict: OnlyStrings = {}; dict.hello = true; di...

Open Graph Description: TypeScript Version: HEAD Search Terms: 23592, index number string keyof Code interface OnlyStrings { [key: string]: boolean; } type OnlyStringsKeys = keyof OnlyStrings; // string | number let dict:...

X Description: TypeScript Version: HEAD Search Terms: 23592, index number string keyof Code interface OnlyStrings { [key: string]: boolean; } type OnlyStringsKeys = keyof OnlyStrings; // string | number let dict:...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Confusing aspects of recent improvements to Index Types","articleBody":"**TypeScript Version:**  HEAD\r\n\r\n**Search Terms:** 23592, index number string keyof \r\n\r\n**Code**\r\n\r\n```ts\r\ninterface OnlyStrings {\r\n  [key: string]: boolean;\r\n}\r\ntype OnlyStringsKeys = keyof OnlyStrings; // string | number\r\nlet dict: OnlyStrings = {};\r\ndict.hello = true;\r\ndict[42] = false;\r\n\r\ninterface OnlyNumbers {\r\n  [idx: number]: boolean;\r\n}\r\ntype OnlyNumbersKeys = keyof OnlyNumbers; // number\r\nlet numbersAllowed: OnlyNumbers = {\r\n  42: false,\r\n  foo: true, // error (as expected)\r\n};\r\nnumbersAllowed.foo = true; // error (as expected)\r\nnumbersAllowed['foo'] = true; // not an error?? Why is a string literal key allowed but only with brackets?\r\nlet s: string = someString();\r\nnumbersAllowed[s] = true; // not an error?? why are arbitrary strings allowed as keys?\r\n\r\ninterface BothStringsAndNumbersLegal {\r\n  [key: string]: boolean;\r\n  [idx: number]: boolean;\r\n}\r\ntype BothStringsAndNumbersLegalKeys = keyof OnlyNumbers; // string | number\r\n\r\ninterface BothStringsAndNumbersNotLegal {\r\n  [keyOrIdx: number | string]: boolean; // Error: An index signature parameter type must be 'string' or 'number'.\r\n}\r\n\r\ninterface CompleteDiffTypes {\r\n  [key: string]: number;\r\n  [idx: number]: boolean; // error, must be assignable to the of the string type\r\n}\r\n\r\ninterface NumbersWithDiffType {\r\n  [key: string]: boolean | string;\r\n  [idx: number]: boolean;\r\n}\r\ntype StringKeys = NumbersWithDiffType[string]; // boolean | string\r\ntype NumericKeys = NumbersWithDiffType[number]; // boolean\r\nlet diffTypes: NumbersWithDiffType = {\r\n   foo: true,\r\n   bar: \"xxx\",\r\n   1: false,\r\n   2: \"yyy\", // error (as expected)\r\n};\r\nlet diffTypes2: NumbersWithDiffType = {}\r\ndiffTypes2[1] = false;\r\ndiffTypes2[2] = \"yyy\"; // Error (as expected)\r\n```\r\n\r\n*** Inconsistent Behavior ***\r\n\r\n1. `BothStringsAndNumbersNotLegal` should be legal, it's just the union type that is returned by `keyof`. It should be sugar for `BothStringsAndNumbersLegal` when the values have the same type. I find it strange that I can't set the index type to the exact type that is returned by `keyof` (without indirection).\r\n2. Setting a string key into an index type that only allows numbers should always be illegal. The variable `numbersAllowed` above only gives an error for some of the ways to set a string key onto the interface.\r\n\r\nOk so I don't think the first two are that controversial. But I think the next one will be:\r\n\r\n3. The type `OnlyStringsKeys` should be `string` and not `string | number` **OR** the types for numbers and strings must be required to be the same.\r\n\r\nYes, I know that is the legacy behavior that is enabled with the special compiler flag. It's a breaking change and that makes it not ideal in the first place. But, beyond that, it's inconsistent.\r\n\r\nI presume the rationale is that integers are cast to strings and so the string type has to be a superset of the number type because the values will be merged into the same key space.\r\n\r\nBut consider this code:\r\n\r\n```ts\r\nlet diffTypes: NumbersWithDiffType = {};\r\ndiffTypes[1] = true;\r\ndiffTypes[\"one\"] = \"astring\";\r\ndiffTypes[\"1\"] = \"ohjoy\";\r\nlet one = diffTypes[1]; // type inferred as boolean\r\nconsole.log([one, typeof one]); // => [ 'ohjoy', 'string' ]\r\n```\r\n\r\nIt's possible for the merged namespace to cause the type of the string to infect the number type resulting in a value that is incorrectly typed.\r\n\r\nI think there's reasonable arguments to be made for one behavior or the other, but I think something has to change. \r\n\r\nAny argument that says that the type `OnlyStringsKeys` has to also include numbers because casting, needs to also say that the value type for number indexes and string indexes has to be the same -- because casting.\r\n\r\nIf numbers are allowed to have their own type, then the argument must be that the risk of namespace collision for strings/numbers is sufficiently low (or a programmers responsibility to manage). By that argument then strings should also be allowed to have their own type that is not required to be a superset.\r\n\r\nThe new code for indexed properties as it stands right now is going to cause me to make a new type:\r\n\r\n```ts\r\ntype Keys\u003cObj extends object> = Extract\u003ckeyof Obj, string>;\r\n```\r\nWhich will replace all the uses of `keyof Obj` for my dictionary types. It's a lot of code changes. I can update this issue with the exact number later. I never use numbers for these types. I don't want to ever pass a number to interfaces unless I said so. But TS allows it:\r\n\r\n```ts\r\ninterface OnlyStrings {\r\n  [key: string]: boolean;\r\n}\r\nlet dict: OnlyStrings = {};\r\ndict.hello = true;\r\ndict[42] = false; // not an error :(\r\n```\r\n\r\nIf I wanted numbers in my type, I would have said so with the type of the `key` for the indexed property (by giving two indexes, or a single one with a union type as I suggest above).\r\n\r\nIf the type checker never allows me to put a number into an object with that interface, then I don't have to worry about namespace collisions. That means the type of `keyof T` can reasonably be `string` unless it's declared to allow numbers. This preserves backwards compatibility for keyof. But it breaks backwards compat for interfaces that are declared with a string index, but are setting numbers in them. In my opinion, this is better. Those interfaces should be updated to declare their index type as being `string | number`, the `keyof` for those types would then match the intent of that interface. This is the kind of type narrowing backwards incompatibility that I'm used to when I upgrade TS.\r\n\r\nI think this change to the `keyof` types is really great in general, but in its current state on master I'm not a fan of some of these rough edges.\r\n\r\n**Related Issues:** https://github.com/Microsoft/TypeScript/pull/23592\r\n","author":{"url":"https://github.com/chriseppstein","@type":"Person","name":"chriseppstein"},"datePublished":"2018-05-09T14:18:25Z","url":"https://github.com/microsoft/TypeScript/issues/23994"}

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:fde00670-745a-5dd8-3e63-56b0ffb245c5
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idAC82:4BB79:C08D94:F6E90D:6B00FF22
html-safe-nonce6878b6f77adcd7d99599874c7ec015979641915f19c42e268f5657a813e258ed
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBQzgyOjRCQjc5OkMwOEQ5NDpGNkU5MEQ6NkIwMEZGMjIiLCJ2aXNpdG9yX2lkIjoiMzE2MDUzNzMwMjQzNDkwNTg5MSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmacf10a40023bf471f7576aff1e0b6a3100a3ebd7b449351170b511cdaf266e47f6
hovercard-subject-tagissue:321589782
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/23994/issue_layout
twitter:imagehttps://opengraph.githubassets.com/a702052f81833153bf16aaaf7e5cad0aff482e64e9899312b9b82cf1ce36ba99/microsoft/TypeScript/issues/23994
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/a702052f81833153bf16aaaf7e5cad0aff482e64e9899312b9b82cf1ce36ba99/microsoft/TypeScript/issues/23994
og:image:altTypeScript Version: HEAD Search Terms: 23592, index number string keyof Code interface OnlyStrings { [key: string]: boolean; } type OnlyStringsKeys = keyof OnlyStrings; // string | number let dict:...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamechriseppstein
hostnamegithub.com
expected-hostnamegithub.com
Nonecb7fa109eca7d4156c889f474306b0e91336055e9adf8fd4684b61e49094d124
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
release2b59d31a4e44f08b7af67a4b67f8fd0af3befe2a
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/microsoft/TypeScript/issues/23994#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F23994
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%2F23994
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/23994
Reloadhttps://github.com/microsoft/TypeScript/issues/23994
Reloadhttps://github.com/microsoft/TypeScript/issues/23994
microsofthttps://github.com/microsoft
TypeScripthttps://github.com/microsoft/TypeScript
Codehttps://github.com/microsoft/TypeScript
Issues5k (5k)https://github.com/microsoft/TypeScript/issues
Pull requests309 (309)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/insights
https://github.com/microsoft/TypeScript
New issuehttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/23994
New issuehttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/23994
Confusing aspects of recent improvements to Index Typeshttps://github.com/microsoft/TypeScript/issues/23994#top
QuestionAn issue which isn't directly actionable in codehttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Question%22
https://github.com/chriseppstein
Chris Eppstein (chriseppstein)https://github.com/chriseppstein
on May 9, 2018https://github.com/microsoft/TypeScript/issues/23994#issue-321589782
#23592https://github.com/microsoft/TypeScript/pull/23592
https://github.com/chriseppstein
Chris Eppstein (chriseppstein)https://github.com/chriseppstein
on May 9, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-387756199
Anders Hejlsberg (@ahejlsberg)https://github.com/ahejlsberg
Mohamed Hegazy (@mhegazy)https://github.com/mhegazy
https://github.com/mhegazy
Mohamed Hegazy (mhegazy)https://github.com/mhegazy
on May 9, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-387797319
#2049https://github.com/microsoft/TypeScript/issues/2049
https://github.com/mhegazy
Mohamed Hegazy (mhegazy)https://github.com/mhegazy
on May 9, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-387798244
https://github.com/chriseppstein
Chris Eppstein (chriseppstein)https://github.com/chriseppstein
on May 9, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-387815718
Mohamed Hegazy (@mhegazy)https://github.com/mhegazy
https://user-images.githubusercontent.com/1839/39828226-1a13d2f8-536f-11e8-83d4-e432a96e75c1.png
https://user-images.githubusercontent.com/1839/39828502-1e676594-5370-11e8-8f83-5b1369874df3.png
https://github.com/weswigham
Wesley Wigham (weswigham)https://github.com/weswigham
on May 10, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-387919584
Mohamed Hegazy (@mhegazy)https://github.com/mhegazy
https://github.com/jack-williams
Jack Williams (jack-williams)https://github.com/jack-williams
on May 10, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-388009736
https://github.com/weswigham
Wesley Wigham (weswigham)https://github.com/weswigham
on May 10, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-388099824
https://github.com/jack-williams
Jack Williams (jack-williams)https://github.com/jack-williams
on May 10, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-388112722
Mohamed Hegazy (mhegazy)https://github.com/mhegazy
QuestionAn issue which isn't directly actionable in codehttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Question%22
on Jul 12, 2018https://github.com/microsoft/TypeScript/issues/23994#event-1731236092
https://github.com/typescript-bot
TypeScript Bot (typescript-bot)https://github.com/typescript-bot
on Jul 25, 2018https://github.com/microsoft/TypeScript/issues/23994#issuecomment-407851865
TypeScript Bot (typescript-bot)https://github.com/typescript-bot
completedhttps://github.com/microsoft/TypeScript/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Jul 25, 2018https://github.com/microsoft/TypeScript/issues/23994#event-1753305919
microsofthttps://github.com/microsoft
on Oct 21, 2025https://github.com/microsoft/TypeScript/issues/23994#event-20415660292
Sign up for freehttps://github.com/signup?return_to=https://github.com/microsoft/TypeScript/issues/23994
Sign in to commenthttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/23994
QuestionAn issue which isn't directly actionable in codehttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Question%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.