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
Domain: github.com
{"@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-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:fde00670-745a-5dd8-3e63-56b0ffb245c5 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | AC82:4BB79:C08D94:F6E90D:6B00FF22 |
| html-safe-nonce | 6878b6f77adcd7d99599874c7ec015979641915f19c42e268f5657a813e258ed |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBQzgyOjRCQjc5OkMwOEQ5NDpGNkU5MEQ6NkIwMEZGMjIiLCJ2aXNpdG9yX2lkIjoiMzE2MDUzNzMwMjQzNDkwNTg5MSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | f10a40023bf471f7576aff1e0b6a3100a3ebd7b449351170b511cdaf266e47f6 |
| hovercard-subject-tag | issue:321589782 |
| 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/23994/issue_layout |
| twitter:image | https://opengraph.githubassets.com/a702052f81833153bf16aaaf7e5cad0aff482e64e9899312b9b82cf1ce36ba99/microsoft/TypeScript/issues/23994 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/a702052f81833153bf16aaaf7e5cad0aff482e64e9899312b9b82cf1ce36ba99/microsoft/TypeScript/issues/23994 |
| og:image:alt | TypeScript 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:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | chriseppstein |
| hostname | github.com |
| expected-hostname | github.com |
| None | cb7fa109eca7d4156c889f474306b0e91336055e9adf8fd4684b61e49094d124 |
| 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 | 2b59d31a4e44f08b7af67a4b67f8fd0af3befe2a |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width