TypeScript

5     Statements

TODO: Describe type checking for statements.

5.1    Variable Statements

Variable statements are extended to include optional type annotations.

VariableDeclaration:  ( Modified )
Identifier   TypeAnnotationopt   Initialiseropt

VariableDeclarationNoIn:  ( Modified )
Identifier   TypeAnnotationopt   InitialiserNoInopt

TypeAnnotation:
:   Type

A variable declaration introduces a variable with the given name in the containing declaration space. The type associated with a variable is determined as follows:

·         If the declaration includes a type annotation, the stated type becomes the type of the variable. If an initializer is present, the initializer expression is contextually typed (see section 4.18) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs.

·         If the declaration includes an initializer but no type annotation, the widened type (see section 3.9) of the initializer expression becomes the type of the property.

·         If the declaration includes neither a type annotation nor an initializer, the type of the variable becomes the Any type.

Multiple declarations for the same variable name in the same declaration space are permitted, provided that each declaration associates the same type with the variable.

Below are some examples of variable declarations and their associated types.

var a;                          // any
var b: number;                  // number
var c = 1;                      // number
var d = { x: 1, y: "hello" };   // { x: number; y: string; }
var e: any = "test";            // any

The following is permitted because all declarations of the single variable ‘x’ associate the same type (Number) with ‘x’.

var x = 1;
var x: number;
if (x == 1) {
    var x = 2;
}

In the following example, all five variables are of the same type, ‘{ x: number; y: number; }’.

interface Point { x: number; y: number; }

var a = { x: 0, y: <number> undefined };
var b: Point = { x: 0; y: undefined };
var c = <Point> { x: 0, y: undefined };
var d: { x: number; y: number; } = { x: 0, y: undefined };
var e = <{ x: number; y: number; }> { x: 0, y: undefined };

5.2    Return Statements

TODO: Within an explicitly typed function, an expression specified in a return statement is contextually typed by the function return type and must be assignable to the function return type.

 

 


TypeScript Language Specification (converted to HTML pages by @Bartvds)

Version 0.9.1

August 2013

Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement  Version 1.0 ('OWF 1.0') as of October 1, 2012. The OWF 1.0 is available at  http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0.

TypeScript is a trademark of Microsoft Corporation.