Title: Problems with comparability between string literal types · Issue #6167 · microsoft/TypeScript · GitHub
Open Graph Title: Problems with comparability between string literal types · Issue #6167 · microsoft/TypeScript
X Title: Problems with comparability between string literal types · Issue #6167 · microsoft/TypeScript
Description: String literals currently only acquire a string literal type if they are contextually typed by another string literal or a union of string literals. They are then comparable and assertable to any string-like type (i.e. string, another st...
Open Graph Description: String literals currently only acquire a string literal type if they are contextually typed by another string literal or a union of string literals. They are then comparable and assertable to any s...
X Description: String literals currently only acquire a string literal type if they are contextually typed by another string literal or a union of string literals. They are then comparable and assertable to any s...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/6167
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Problems with comparability between string literal types","articleBody":"String literals currently only acquire a string literal type if they are contextually typed by another string literal or a union of string literals. They are then comparable and assertable to any string-like type (i.e. `string`, another string literal type, and any union with a string literal type inside of it).\n\nBy and large, this gives us the behavior you want; however, there are some problems with this approach.\n# Problems\n## `switch`/`case`\n\nThis is valid, which seems bad:\n\n``` ts\nlet x: \"foo\" = \"foo\";\n// ...\nswitch (x) {\n case \"bar\":\n console.log(\"wat\");\n}\n```\n\nWhen can `x` be `\"bar\"`? Without bypassing the type system, clearly never.\n## Equality\n\nThis is valid, which seems bad:\n\n``` ts\nlet x: \"foo\";\n// ...\nif (x === \"bar\") {\n}\n```\n\nThis is similar to the `switch` statement example. When will this condition be true? Again, without fooling the type system, it can't be.\n## Type assertions\n\nThese are both valid, which seems bad:\n\n``` ts\nlet x = \"hello\" as \"world\";\nlet y = \u003c\"bar\" | \"baz\">\"foo\";\n```\n\nThis is where we allow you to lie to the type system. This is probably way too lenient, so I'd say that this is bad.\n# Solutions?\n\nMost of the solutions here would require us to tighten our rules regarding allowing these operations between string-like entities. Essentially, we would need to capture some of the same behavior originally proposed in the pull request about a new \"comparable\" type relationship (#5517).\n## Widening\n\nWhy don't we have every string literal start out with a string literal type and widen to `string` when needed? We could certainly do that, but the question is when does a string literal type need to be widened?\n\nTo quote @JsonFreeman on https://github.com/Microsoft/TypeScript/issues/5300#issuecomment-150657208, widening as it would stand today would be a problem for type argument inference:\n\n> I think the biggest issue with the widening approach is that types are widened after type argument inference, which is an issue we have discussed before. It makes it so that any string literals that get inferred are automatically widened to string, which is a little unfortunate.\n\nHere's the problem Jason was talking about\n\n``` ts\ndeclare function f\u003cT>(x: T): T;\n\nlet x = f(\"hello\");\n```\n\nHere, we would always widen to `string` after picking a type for `T`. And even if we didn't, we'd still have other issues:\n\n``` ts\ndeclare function f\u003cT>(x: T, y: T): T;\n\nlet x = f(\"hello\", \"world\");\n```\n\nWhen we try to figure out what `T` should be, we'd have two different types: `\"hello\"` and `\"world`. Usually, when trying to infer `T` given the choice between something like `number` and `string`, we'll error. We could change this behavior, and while **it might be more desirable to infer `\"hello\" | \"world\"`** here, it would certainly be less consistent.\n# Contextually type `case` expressions\n\nFor the `switch`/`case` example, we could contextually type each `case` clause expression by the type of the `switch` expression:\n\n``` ts\nlet x: \"foo\" | \"bar;\n// ...\nswitch (x) {\n case \"baz:\": // \u003c- error: type '\"baz\"' is not compatible with '\"foo\" | \"bar\"'\n console.log(\"wat\");\n}\n```\n\nBut what about the other way around? We can't contextually type in both directions, because that would create a circularity. A `case` clause expression would try to grab a contextual type from the `switch` expression, which would try to grab the contextual type from its `case` clauses... etc.\n\nSo we could just make things unidirectional, which still has undesirable results\n\n``` ts\nlet x: \"foo\" | \"bar;\n// ...\nswitch (\"baz\") {\n case x: // \u003c- okay: type '\"foo\" | \"bar\"' is compatible with 'string'\n console.log(\"wat\");\n}\n```\n\nAnd admittedly, that code is less likely to be written, but really, what is fundamentally different about the first `switch (x)` example and the following?\n\n``` ts\nlet x: \"foo\" | \"bar\";\n// ...\nif (x === \"baz\") { // \u003c- okay: type '\"foo\" | \"bar\"' is compatible with 'string'\n console.log(\"wat\");\n}\n```\n\nClearly you want an error here too, so it would be kind of weird to specially treat `switch` statements, but not equality comparisons.\n# Come up with a some new flow of information, like contextual typing\n\nFor equality checks, it'd be nice to have something that can flow both ways. For instance, in this example\n\n``` ts\nlet x: \"foo\" | \"bar\";\n// ...\nif (x === \"baz\") {\n console.log(\"wat\");\n}\n```\n\nyou want `\"baz\"` to grab the type of `x`, **independent of this type relation**, and apply the same sort of information towards creating a string literal type as you would given a contextual type. Since `x` would have the type of `\"foo\" | \"bar\"`, which is a union containing string literal types, `\"baz\"` would acquire its string literal type for the purpose of this check.\n\nYou wouldn't end up catching the following\n\n``` ts\nif (\"hello\" === \"world\") {\n // ...\n}\n```\n\nbecause each side would just have type `string`, and inform the other side with the type `string`. But you can already do that today, and this is a fairly silly case anyway, so it probably doesn't matter.\n\nThe biggest question is how we plan to implement this. It would certainly need a proposal.\n## Come up with some ad hoc checks\n\nWe could come up with some weak checks in these positions to figure out if the user is likely making an error. This would need a proposal.\n","author":{"url":"https://github.com/DanielRosenwasser","@type":"Person","name":"DanielRosenwasser"},"datePublished":"2015-12-19T00:58:11Z","url":"https://github.com/microsoft/TypeScript/issues/6167"}
| 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:a51262c5-dcbc-b2e9-33ae-3dfad741c0ab |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E8FC:2C75BB:129C25:1911E2:6AFBDD83 |
| html-safe-nonce | ebc4514c404cc5c3b816e464daf94f7cecc617dd88dac4fd723dda18b82b1366 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFOEZDOjJDNzVCQjoxMjlDMjU6MTkxMUUyOjZBRkJERDgzIiwidmlzaXRvcl9pZCI6IjQ3NzM2MDQzOTY0NzAwMTk4NyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 28895a3dc4bd658edc9f5add1e550986904d808fd0b5851239b1742fdcf6dc94 |
| hovercard-subject-tag | issue:123050404 |
| 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/6167/issue_layout |
| twitter:image | https://opengraph.githubassets.com/3df590b4f09083b59fa039174c81492eda250b32cc03b05ca86f33c1e13ec9c3/microsoft/TypeScript/issues/6167 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/3df590b4f09083b59fa039174c81492eda250b32cc03b05ca86f33c1e13ec9c3/microsoft/TypeScript/issues/6167 |
| og:image:alt | String literals currently only acquire a string literal type if they are contextually typed by another string literal or a union of string literals. They are then comparable and assertable to any s... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | DanielRosenwasser |
| 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