Example from Chapter 4.18

Topics: Language Specification
Dec 5, 2013 at 6:09 PM
In chapter 4.18, the following declaration is provided
var f: (s: string) => string;
The text then brings the following example:
For example, given the declaration of the variable ‘f’ above, the assignment
f = s => s.toLowerCase(); 
causes the function expression to be contextually typed, inferring the String primitive type for > ‘s’.
However, simply enclosing the construct in parentheses
f = (s => s.toLowerCase()); 
causes the function expression to be processed without a contextual type, now inferring ‘s’ and the result of the function to be of type Any as no type annotations are present.
However, the following snippet will not compile. But from what I understand if the Any type is inferred from this version, there should be no errors. I want to note that I actually think it should be possible and okay to detect the error because the declaration is clear, but it's just not what I expect from reading the text:
var f: (s: string) => string;
f = (s => s.toLowerCase());

f(1); // error
Dec 5, 2013 at 8:14 PM
The type of a variable does not change after its declaration, regardless of what assignments happen to it. The assignment on the second line of your last example is irrelevant to whether or not f(1); is an error.

The part about the expression (s => s.toLowerCase()) being determined to have a return type of any applies to the expression itself. In this case, the type of that expression is only considered for the purposes of checking assignment compatibility with f.
Dec 5, 2013 at 8:23 PM
Contextual typing allows types from declarations to be 'pushed' to values which had no explicit type annotation. It doesn't cause types to flow in the other direction and make the type of an explicitly typed declaration change based on the argument values provided. It would be very strange for f to be typed as string => string but for that to be a lie depending on how someone later initialized it. When contextual typing is not applied in the example above f is still string => string, it is just being initialized with a function that is any => any which is a valid assignment.
Dec 5, 2013 at 8:53 PM
Thanks you guys, that makes sense. Though technically worded correctly, maybe it's something where the spec could be a little clearer? I could imagine not being the only one wondering about this, but who knows. :)