-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type inference for constant objects with string literal types #32139
Comments
The variable What you want can be achieve with the "const contexts" feature introduced in TypeScript 3.4: #29510
This would definitely be a breaking change in existing code. If it would infer |
Yes, "const contexts" make the code look better here, I didn't know about them.
I agree, so what I was actually thinking about was more similar to automatic inference of "const context" in some cases. In my example "obj" cannot be changed from the outside of the function and it is not changed inside, so in this particular case the compiler could infer that |
I see. Personally I think it's really not worth the additional code (complexity) and performance cost (the analysis), when we already have a very good feature to solve this without hassle: const contexts. |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Hi!
Let's say that I have this code:
For the
first
object the compiler can infer type ofhello
as a string literal type and outputs no errors. However, for the second object can't infer this, althoughobj
is a constant object, and throws an error.It would be nice to have automatic inference here. For example, in Flow types are inferred here automatically and the same code passes type checks without errors.
Addition: specifying the string type literal explicitly helps:
but makes the code look verbose.
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: