Closed
Description
TypeScript Version: 2.7.0-dev.20171124
Code
enum Item {
potato = "potato",
cucumber = "cucumber"
}
// inferred type is `() => Item`
const getPotato1 = () => Item.potato;
// type assertion works
const getPotato2: () => Item.potato = () => Item.potato;
Expected behavior:
Type of getPotato1
should be inferred as () => Item.potato
.
Actual behavior:
Type of getPotato1
is "needlessly" widened to () => Item
.
cc @OliverJAsh
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
ahejlsberg commentedon Nov 25, 2017
This is working as intended. See #10676 (comment).
OliverJAsh commentedon Nov 25, 2017
@ahejlsberg
Interesting, thanks for the linking to that explanation!
#10676 (comment)
Here is an example where the return type is not a singleton literal type but a union of objects containing literal types, and the compiler still appears to widen both literal types to their enum union type:
Is this also expected behaviour, or a separate issue?
ahejlsberg commentedon Nov 26, 2017
@OliverJAsh My comment above was regarding literal types as the actual return type. In your example the return type is a union of object types, and the literal types are widened because they are inferred for a mutable location (i.e. a property in an object literal). That is the expected behavior.
OliverJAsh commentedon Nov 26, 2017
Aha, good to know, thanks. Here's an example for anyone else who might be interested:
OliverJAsh commentedon Nov 26, 2017
Also for anyone else who is interested, here is some discussion about widening in object literals and a proposal to change this #20195
typescript-bot commentedon Dec 11, 2017
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.