TypeScript Language Specification
TypeScript Language Specification
TypeScript Language Specification
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
eference (section 4.1) and the type of the non-compound operation to be assignable to the type of<br />
VarExpr.<br />
4.18 Contextually Typed Expressions<br />
In certain situations, parameter and return types of function expressions are automatically inferred from<br />
the contexts in which the function expressions occur. For example, given the declaration<br />
the assignment<br />
var f: (s: string) => string;<br />
f = function(s) { return s.toLowerCase(); }<br />
infers the type of the ‘s’ parameter to be the String primitive type even though there is no type annotation<br />
to that effect. The function expression is said to be contextually typed by the variable to which it is being<br />
assigned. Contextual typing occurs in the following situations:<br />
� In variable and member declarations with a type annotation and an initializer, the initializer<br />
expression is contextually typed by the type of the variable or property.<br />
� In assignment expressions, the right hand expression is contextually typed by the type of the left<br />
hand expression.<br />
� In typed function calls, argument expressions are contextually typed by their parameter types.<br />
� In return statements, if the containing function has a known return type, the expression is<br />
contextually typed by that return type. A function’s return type is known if the function includes a<br />
return type annotation or is itself contextually typed.<br />
� In contextually typed object literals, property assignments are contextually typed by their property<br />
types.<br />
� In contextually typed array literals, element expressions are contextually typed by the array<br />
element type.<br />
Contextual typing of an expression e by a type T proceeds as follows:<br />
� If e is an ObjectLiteral and T is an object type, e is processed with the contextual type T, as<br />
described in section 4.5.<br />
� If e is an ArrayLiteral and T is an array type, e is processed with the contextual type T, as described<br />
in section 4.6.<br />
� If e is a FunctionExpression or ArrowFunctionExpression with no parameter or return type<br />
annotations and T is an object type with exactly one call signature, e is processed with the<br />
contextual type T, as described in section 4.9.<br />
� Otherwise, e is processed without a contextual type.<br />
The rules above require expressions be of the exact syntactic forms specified in order to be processed as<br />
contextually typed constructs. For example, given the declaration of the variable ‘f’ above, the assignment<br />
f = s => s.toLowerCase();<br />
44