-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Suggestion: Infer literal types for getter only properties that return literals #11467
Comments
Probably a bug in spec, IMHO.
And in #6532
An implicitly readonly property, namely get only accessor, should also be inferred as literal type if possible.
The above rule does not apply here because the contextual type Stylesheet.create does not have literal type. |
If #11535 gets adopted, this could be accomplished via const styles = StyleSheet.create({
text: Object.freeze({
position: 'absolute',
top: 0,
left: 0
})
}); |
Possibly related: function id<T>(x: T) { return x; }
function wrap<T>(value: T): { readonly value: T } { return { value }; }
const s: "s" = id("s"); // Works, inferred id<"s">
const vs: { readonly value: "s" } = wrap("s"); // Error, inferred wrap<string> |
Interesting, it seems like the literal type is only inferred for function wrap<T extends string>(value: T);
function wrap<T>(value: T);
function wrap<T>(value: T): { readonly value: T } { return { value }; } |
Experience in real code shows that getters sometimes have function-like behavior (where you would want the nonliteral type) and sometimes have property-like behavior (where you may want the literal type). In general, mostly due to back compat problems, we defer to nonliteral types when it isn't clear from context that you need one. |
@RyanCavanaugh thank you for explaining the reasoning, I really appreciate it. |
@RyanCavanaugh Shall I make a separate issue for my earlier comment? |
Suggestion: Infer literal types for getter only properties that return literals.
This suggestion arose from reading #11465 the example below comes directly from that issue.
TypeScript Version: nightly (2.0.0-dev.20161008)
Code
I tried a different workaround than the ones presented by @jovdb in #11465
Expected behavior:
The type of
text.position
is inferred as'absolute'
Actual behavior:
The type of
text.position
is inferred asstring
My reasoning here is that while the following rules, outlined in #10676, make complete sense in general, they are not ideal for getter only properties
I am not sure if both of these rules apply here or only the second.
The text was updated successfully, but these errors were encountered: