of 97
Current View
TypeScript
Language Specification
Version 0.8
October
2012
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.
i
Table of Contents
1
Introduction
................................
................................
................................
................................
................................
...................
1
1.1
Ambient Declarations
................................
................................
................................
................................
.....................
3
1.2
Function Types
................................
................................
................................
................................
................................
..
3
1.3
Object Types
................................
................................
................................
................................
................................
......
4
1.4
Structural Subtyping
................................
................................
................................
................................
.......................
6
1.5
Contextual Typing
................................
................................
................................
................................
............................
7
1.6
Classes
................................
................................
................................
................................
................................
..................
7
1.7
Modules
................................
................................
................................
................................
................................
............
10
2
Basic Concepts
................................
................................
................................
................................
................................
..........
13
2.1
Grammar Conventions
................................
................................
................................
................................
................
13
2.2
Declarations
................................
................................
................................
................................
................................
.....
13
2.3
Scopes
................................
................................
................................
................................
................................
...............
15
3
Types
................................
................................
................................
................................
................................
.............................
17
3.1
The Any Type
................................
................................
................................
................................
................................
..
18
3.2
Primitive
Types
................................
................................
................................
................................
...............................
18
3.2.1
The Number Type
................................
................................
................................
................................
....................
18
3.2.2
The Boolean Type
................................
................................
................................
................................
....................
19
3.2.3
The String Type
................................
................................
................................
................................
.........................
19
3.2.4
The Null Type
................................
................................
................................
................................
.............................
19
3.2.5
The Undefined Type
................................
................................
................................
................................
................
20
3.3
Object Types
................................
................................
................................
................................
................................
...
20
3.4
The Void Type
................................
................................
................................
................................
................................
.
21
3.5
Specifying Types
................................
................................
................................
................................
............................
22
3.5.1
Predefined Types
................................
................................
................................
................................
......................
22
3.5.2
Type Names
................................
................................
................................
................................
...............................
23
3.5.3
Object Type Literals
................................
................................
................................
................................
.................
23
3.5.4
Array Type Literals
................................
................................
................................
................................
...................
26
3.5.5
Function Type Literals
................................
................................
................................
................................
............
26
3.5.6
Constructor Type Literals
................................
................................
................................
................................
......
27
3.6
Type Relationships
................................
................................
................................
................................
........................
27
3.6.1
Type identity
................................
................................
................................
................................
..............................
28
3.6.2
Subtypes and Supertypes
................................
................................
................................
................................
.....
28
3.6.3
Assignment Compatibility
................................
................................
................................
................................
....
28
3.7
Widened Types
................................
................................
................................
................................
..............................
29
3.8
The Best Common Type
................................
................................
................................
................................
.............
30
4
Expressions
................................
................................
................................
................................
................................
.................
31
4.1
Values and References
................................
................................
................................
................................
................
31
4.
2
The this Keyword
................................
................................
................................
................................
...........................
31
ii
4.3
Identifiers
................................
................................
................................
................................
................................
..........
32
4.4
Literals
................................
................................
................................
................................
................................
...............
32
4.5
Object Literals
................................
................................
................................
................................
................................
.
32
4.6
Array Literals
................................
................................
................................
................................
................................
...
32
4.7
Parent
heses
................................
................................
................................
................................
................................
.....
33
4.8
The super Keyword
................................
................................
................................
................................
.......................
33
4.8.1
Super Calls
................................
................................
................................
................................
................................
..
33
4.8.2
Super Property Access
................................
................................
................................
................................
...........
33
4.9
Function Expressions
................................
................................
................................
................................
...................
34
4.9.1
Standard Function Expressions
................................
................................
................................
...........................
34
4.9.2
Arrow Function Expressions
................................
................................
................................
................................
.
35
4.10
Property Access
................................
................................
................................
................................
.............................
36
4.11
The new Operator
................................
................................
................................
................................
.........................
37
4.12
Function Ca
lls
................................
................................
................................
................................
................................
.
37
4.13
Type Assertions
................................
................................
................................
................................
..............................
38
4.14
Unary Operators
................................
................................
................................
................................
............................
39
4.14.1
The ++ and
--
operators
................................
................................
................................
................................
.......
40
4.14.2
The +,
, and ~ operators
................................
................................
................................
................................
.....
40
4.14.3
T
he ! operator
................................
................................
................................
................................
............................
40
4.14.4
The delete Operator
................................
................................
................................
................................
................
40
4.14.5
The void Operator
................................
................................
................................
................................
...................
40
4.14
.6
The typeof Operator
................................
................................
................................
................................
...............
40
4.15
Binary Operators
................................
................................
................................
................................
...........................
40
4.15.1
The *, /, %,
, <<, >>, >>>, &, ^, and | operators
................................
................................
......................
41
4.15.2
The + operator
................................
................................
................................
................................
..........................
41
4.15.3
The <, >, <=, >=, ==, !=, ===, and !== operators
................................
................................
...................
42
4.15.4
The instanceof operator
................................
................................
................................
................................
........
42
4.15.5
The in operator
................................
................................
................................
................................
.........................
42
4.15.6
The &&
operator
................................
................................
................................
................................
......................
42
4.15.7
The || operator
................................
................................
................................
................................
...........................
43
4.16
The Conditional Operator
................................
................................
................................
................................
..........
43
4.17
Assignment Operators
................................
................................
................................
................................
................
43
4.18
Contextually Typed Expressions
................................
................................
................................
..............................
44
5
Statements
................................
................................
................................
................................
................................
..................
47
5.1
Variable Sta
tements
................................
................................
................................
................................
.....................
47
6
Functions
................................
................................
................................
................................
................................
.....................
49
6.1
Function Declarations
................................
................................
................................
................................
..................
49
6.2
Function Signatures
................................
................................
................................
................................
.....................
49
6.3
Function Overloads
................................
................................
................................
................................
......................
51
6.4
Function Impleme
ntations
................................
................................
................................
................................
........
52
6.5
Code Generation
................................
................................
................................
................................
...........................
53
iii
7
Interfaces
................................
................................
................................
................................
................................
.....................
55
7.1
Interface Declarations
................................
................................
................................
................................
.................
55
7.2
Dynamic Type Checks
................................
................................
................................
................................
.................
56
8
Classes
................................
................................
................................
................................
................................
..........................
59
8.1
Class Declarations
................................
................................
................................
................................
.........................
59
8.1.1
Class Heritage Specification
................................
................................
................................
................................
60
8.1.2
Class Body
................................
................................
................................
................................
................................
...
61
8.2
Members
................................
................................
................................
................................
................................
...........
61
8.2.1
Accessibility
................................
................................
................................
................................
................................
62
8.2.2
Inheritance and Overriding
................................
................................
................................
................................
..
62
8.2.3
Class Instance Types
................................
................................
................................
................................
...............
62
8.2.4
Constructor Function Types
................................
................................
................................
................................
.
63
8.3
Constructor Declarations
................................
................................
................................
................................
...........
64
8.3.1
Constructor Parameters
................................
................................
................................
................................
.........
64
8.3.2
Super Calls
................................
................................
................................
................................
................................
..
65
8.3.3
Automatic Constructors
................................
................................
................................
................................
........
66
8.4
Member Declarations
................................
................................
................................
................................
..................
66
8.4.1
Member Variable Declarations
................................
................................
................................
...........................
67
8.4.2
Member Function Declarations
................................
................................
................................
..........................
68
8.4.3
Member Accessor Declarations
................................
................................
................................
..........................
69
8.5
Code Generation
................................
................................
................................
................................
...........................
70
8.5.1
Classes Without Extends Clauses
................................
................................
................................
.......................
70
8.5.2
Classes With Extends Clauses
................................
................................
................................
..............................
72
9
Programs and Modules
................................
................................
................................
................................
.........................
75
9.1
Programs
................................
................................
................................
................................
................................
..........
75
9.1.1
Source Files Dependencies
................................
................................
................................
................................
...
76
9.2
Module Declarations
................................
................................
................................
................................
....................
77
9.2.1
Export Declarations
................................
................................
................................
................................
.................
77
9.2.2
Import Declarations
................................
................................
................................
................................
................
78
9.2.3
Module Identifiers
................................
................................
................................
................................
...................
79
9.3
Internal Modules
................................
................................
................................
................................
...........................
80
9.4
External Modules
................................
................................
................................
................................
...........................
83
9.4.1
Ex
ternal Module Names
................................
................................
................................
................................
........
83
9.4.2
CommonJS Modules
................................
................................
................................
................................
...............
84
9.4.3
AMD Modules
................................
................................
................................
................................
...........................
86
9.5
Code Generation
................................
................................
................................
................................
...........................
86
9.5.1
In
ternal Modules
................................
................................
................................
................................
......................
86
10
Ambients
................................
................................
................................
................................
................................
......................
89
10.1
Ambient Declarations
................................
................................
................................
................................
..................
89
10.1.1
Ambient Variable Declarations
................................
................................
................................
...........................
89
10.1.2
Ambient Function Declarations
................................
................................
................................
..........................
89
iv
10.1.3
Ambient Class Declarations
................................
................................
................................
................................
.
90
10.1.4
Ambient Module Declarations
................................
................................
................................
............................
90
10.2
Declaration Source Files
................................
................................
................................
................................
.............
91
1
1
Introduction
Web applications such as e
-
mail, maps, document editing, and collaboration tools are becoming an
increasingly important
part of the everyday computing.
We designed
TypeScript
to meet the needs of the
JavaScript programming teams
that
build
and maintain
large JavaScript programs
such as web
applications
.
TypeScript
helps programming teams to define interfaces between softwar
e components
and to gain insight into the behavior of existing JavaScript libraries.
TypeScript
also enables teams to
reduce naming conflicts by organizing their code into dynamically
-
loadable modules.
TypeScript
s
optional type system enables JavaScript p
rogrammers to use highly
-
productive development tools and
practices: static checking, symbol
-
based navigation, statement completion, and code re
-
factoring.
TypeScript
is a syntactic sugar for JavaScript.
TypeScript
syntax is a superset of Ecmascript 5 (ES5
) syntax.
Every JavaScript program is also a
TypeScript
program. The
TypeScript
compiler performs only file
-
local
transformations on
TypeScript
programs and does not re
-
order variables declared in
TypeScript
. This
leads to JavaScript output that closely ma
tches the
TypeScript
input.
TypeScript
does not transform
variable names, making tractable the direct debugging of emitted JavaScript.
TypeScript
optionally
provides source maps, enabling source
-
level debugging.
TypeScript
tools typically emit JavaScript u
pon
file save, preserving the test, edit, refresh cycle commonly used in JavaScript development.
TypeScript
syntax includes
several
proposed
features of Ecmascript 6 (ES6), including
classes and modules.
Classes enable programmers to express common object
-
oriented patterns in a standard way, making
features like inheritance more readable and interoperable. Modules enable programmers to organize their
code into components while avoiding naming conflicts. The
TypeScript
compiler provides module code
generatio
n options that support either static or dynamic loading of module contents.
TypeScript
also provides to JavaScript programmers a system of optional type annotations. These type
annotations are like the JSDoc comments found in the Closure system, but in
Typ
eScript
they are
integrated directly into the language syntax. This integration makes the code more readable and reduces
the maintenance cost of synchronizing type annotations with their corresponding variables.
The
TypeScript
type system enables programme
rs to express limits on the capabilities of JavaScript
objects, and to use tools that enforce these limits. To minimize the number of annotations needed for
tools to become useful, the
TypeScript
type system makes extensive use of type inference. For examp
le,
from the following statement,
TypeScript
will infer that the variable ‘i’ has the type number.
var
i = 0;
TypeScript
will infer from the following function definition that the function f has return type string.
function
f() {
return
"hello"
;
}
2
To benefit from this inference, a programmer can use the
TypeScript
language service. For example, a
code editor can incorporate the
TypeScript
language service and use the service to find the members of a
string object as in the following screen shot.
I
n this example, the programmer benefits from type inference without providing type annotations. Some
beneficial tools, however, do require the programmer to provide type annotations. In
TypeScript
, we can
express a parameter requirement as in the following
code fragment.
function
f(s:
string
) {
return
s;
}
f({});
// E
rror
f(
"hello"
);
// O
k
This optional ty
pe annotation on the parameter ‘s’
lets the
TypeScript
type checker know that th
e
programmer expects parameter ‘s’ to be of type ‘string’. With
in the body of function ‘f’, tools can assume
‘s’ is of type ‘string’
and provide operator type checking and member completion consistent with this
assumption. Tools can also signal an error on the first call to
f
, because
f
expects a string, not an ob
ject,
as its parameter.
For the function ‘f’, the TypeScript compiler will emit the following JavaScript code:
function
f(s)
{
return
s;
}
In the JavaScript output, all type
annotations have been erased.
In general, TypeScript erases all type
information before emiting JavaScript.
10
Section
8
provides additional information about classes.
1.7
Modules
Classes and interfaces support large
-
scale JavaScript development by providing a mechanism for
describing how to use a software component that can be separated from th
at component’s
impl
ementation.
TypeScript
enforces
encapsulation
of implementation in classes at design time (by
restricting use of private members), but cannot enforce encapsulation at runtime because all object
propert
ies are accessible at runtime.
Future versions of JavaS
cript may provide
private names
which would
enable runtime enforcement of private members.
In the current version of JavaScript, the only way to enforce encapsulation at runtime is to use the module
pattern: encapsulate private fields and me
thods using clo
sure variables.
The module pattern is a natural
way to
provide organizational structure and dynamic loading options by
draw
ing
a boundary around a
software com
ponent.
A module can also provide the ability to introduce namespaces, avoiding use of the
global namespace for most software components.
The following example illustrates the JavaScript module pattern.
(
function
(
exports
)
{
var
key
=
generateSecretKey
();
function
sendMessage
(
message
)
{
sendSecureMessage
(
message
,
key
);
}
exports.sendMessage = sendMessage;
})(
MessageModule
);
This example illustrates the two essential elements of the module pattern: a
module
closure
and a
module
object
.
The mo
dule closure is a function that encapsulates the module’s implementation, in this case the
variable ‘key’ a
nd the function ‘sendMessage’.
The module object contains the exported variable
s and
functions of the module.
Simple modules may create
and return th
e module object.
The module above
takes the module object as a parameter, ‘exports’, and adds the ‘sendMessage’
property to the module
object.
This
augmentation
approach simplifies dynamic loading of modules and also supports separation
of mo
dule code into
multiple files.
The example assumes that an outer lexical scope defines the functions ‘generateSecretKey’ and
‘sendSecureMessage’; it also assumes that the outer scope has assigned the module object to
the variable
‘MessageModule’.
TypeScript
modules prov
ide a mechanism for succinctly
expressing the module pattern.
In
TypeScript
,
programmers can combine the module pattern with the class pattern by nesting modules and c
lasses
within an outer module.
The following example shows the definition and use of a s
imple module.
11
module
M
{
var
s
=
"hello";
export
function
f()
{
return
s;
}
}
M.f();
M.s;
// Error,
s is not exported
In this example, variable ‘s’ is a private feature of the module, but function ‘f’ is exported from the module
and accessible
to code outside of the module.
If we were to describe the effect of module ‘M’ in terms of
interfaces and variables, we would writ
e
interface
M
{
f
():
string
;
}
var
M
:
M
;
The interface ‘M’ summarizes the externally vi
sible behavior of module ‘M’.
In this example, we can use the
same name for the interface as for the initialized variable because in
TypeScript
type names and variab
le
names do not conflict: each lexical scope contains a variable declaration space and type declaration space
(see Section
2.2
for more details).
Module ‘M’ is an e
xample of an
internal
module, because it is nested within the
global
module (see
Section
9
for more details).
The
TypeScript
compiler emits the following JavaScript code for this module.
var
M;
(
function
(M)
{
var
s
=
"hello"
;
function
f()
{
return
s;
}
M.f
=
f;
})(M||(M={}));
In this case, the compiler assumes that the module object resides in global var
iable ‘M’, which may or may
not have been initialized
to the desired module object.
TypeScript
also supports
external
modules, which are files that contain top
-
level
export
and
import
directives.
For this type of module the
TypeScript
compiler will emit co
de whose module closure and
module object implementation vary according to the specified dynamic loading system, for example, the
Asynch
ro
nous Module Definition system.
13
2
Basic Concepts
The remainder of this doc
ument is the formal specification of the
TypeScript
programming language and
is intended to be read as an adjunct to the
ECMAScript Language Specification
(
specifical
ly, the
ECMA
-
262 Standard
, 5
th
Edition
).
This document
describes the
syntactic grammar added by
TypeScript
along
with the
compile
-
time processing and type checking performed by the
TypeScript
compiler, but it
only
minimally discusses
the run
-
time
behavior of programs since that
is co
vered by the ECMAScript
specification
.
2.1
Grammar Conventions
The syntactic grammar added by
TypeScript
language is specified throughout
this document
using the
existing
conventions
and production names
of the ECMAScript
grammar.
In places where
TypeScript
augments an existing grammar production it is so noted. For example:
CallExpression: ( Modified )
...
super
Arguments
super
.
Identifier
The ‘
( Modified )
’ annotation indicates that an existing grammar production is
being replaced, and the ‘...’
references the contents of the original grammar production.
2.2
Declarations
Declarations introduce
name
s
in the
declaration space
s
to
which
they
belong
.
It is an error to have two
names with same spelling in the same declaration s
pace.
Declaration spaces
exist
as follows:
The global module has a
declaration space for global members (variables, functions,
modules, and
constructor functions
), and a declaration space for global types (
modules,
classes
,
and interfaces).
E
ach module
body
has
a declaration space for
local members
(
variables, functi
ons, modules, and
constructor functions
)
,
and a declaration space
for local
types (
modules,
class
es
,
and interface
s)
.
Every declaration
(whether local or exported)
in a module contributes to
one or bo
th of the
se
declaration spaces.
E
ach
internal
or external
module
has
a declaration space for exported members and a declar
ation
space for exported types.
All export declarations
in the module
contribute to these declaration
spaces.
Each
internal
m
odule’s export declaration spaces are shared with other
internal
modules
that have the same root module and the same qualified name starting from that root module.
Each interface type
has
a declaration space for its members.
An interface’s declaration spac
e is
shared with other interfaces that have the same root module and the same qualified name
starting from that root module.
Each
object
type
literal
has
a declaration space for its members.
23
3.5.2
Type Names
Class
, module,
and interface declarations introduce
named types
which may be referenced by their name
wherever a type is expected.
Resolution of a
ModuleOrTypeName
consisting of a single identifier is described in section
2.3
.
Resolution of a
ModuleOrT
ypeName
of the form
M.N
, where
M
is a
ModuleName
and
N
is an
Identifier
,
proceeds by first resolving
the module name
M
. If the resolution of
M
is successful and
the resulting
mo
dule contains an exported class, module, or
interface member
N
, then
M.N
refers to that member.
Otherwise,
M.N
is undefined.
A
TypeName
is a
ModuleOrTypeName
that can refer to a class, module, or i
nterface. When a
TypeName
refers to a module it denotes the object type associated with the module.
When resolution of a
TypeName
fails, an error is reported and the Any type is substituted.
A
ModuleName
is a
ModuleOrTypeName
that must refer to a module.
3.5.3
Object Type Literals
A
n object
type
literal
defines an object type by specifying
the set of members that are statically
considered to be present in instances of the type.
Object type l
iteral
s
can be given names using interface
declarations but are otherwis
e
anonymous
.
ObjectType:
{
TypeBody
}
TypeBody:
TypeMemberList
opt
TypeMemberList
;
TypeMemberList:
TypeMember
TypeMemberList
;
TypeMember
TypeMember:
CallSignature
ConstructSignature
IndexSignature
PropertySignature
FunctionSignature
The members
of a
n object type
literal are specified
as
a
combination of call, construct, index
, property and
function signatures. The signatures are separated by
semicolons
and enclosed in
curly braces.
89
10
Ambients
Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations
differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new
variables,
functions, classes, or modules, ambient declarations provide type information for entities that
exist “ambiently” and are included in a program by external means, for example by referencing a
JavaScript library in a <script/> tag.
In implementation source
files (files with a ‘.ts’ extension), ambient declarations are written using the
declare
keyword. In declaration source files (files with a ‘.d.ts’ extension), a
declare
keyword is implicitly
present on every declaration.
TODO: Finish this
chapter
.
10.1
Ambien
t Declarations
Ambient declarations can declare variables, functions, classes, or modules.
AmbientDeclaration:
declare
AmbientVariableDeclaration
declare
AmbientFunctionDeclaration
declare
AmbientClassDeclaration
declare
AmbientModuleDeclaration
10.1.1
Ambient Variable Declarations
An ambient variable declaration introduces a variable in the containing declaration space.
AmbientVariableDeclaration:
var
Identifier TypeAnnotation
opt
;
An ambient variable declaration may optionally include a type
annotation. If no type annotation is
present, the variable is assumed to have type Any.
An ambient variable declaration does not permit an initializer expression to be present.
10.1.2
Ambient Function Declarations
An ambient function declaration introduces a func
tion in the containing declaration space.
AmbientFunctionDeclaration:
function
FunctionSignature
;
Ambient functions may be overloaded by specifying multiple ambient function declarations with the same
name, but no two declarations for the same name ma
y have the same number of parameters and identical
parameter types in the respective positions.
90
Ambient function declarations cannot specify a function bodies and
do not permit default parameter
values.
10.1.3
Ambient Class Declarations
A
n ambient class declarati
on
declares
a class instance type and a constructor function
in the containing
module.
AmbientClassDeclaration:
class
Identifier ClassHeritage
{
AmbientClassBody
}
AmbientClassBody:
AmbientClassBodyElements
opt
AmbientClassBodyElements:
AmbientCla
ssBodyElement
AmbientClassBodyElements AmbientClassBodyElement
AmbientClassBodyElement:
AmbientConstructorDeclaration
AmbientMemberDeclaration
AmbientStaticDeclaration
AmbientConstructorDeclaration:
constructor
(
ParameterList
opt
)
;
AmbientMemberDeclaration:
PublicOrPrivate
opt
Identifier TypeAnnotation
opt
;
PublicOrPrivate
opt
FunctionSignature
;
AmbientStaticDeclaration:
static
Identifier TypeAnnotation
opt
;
static
FunctionSignature
;
10.1.4
Ambient Module Declarations
An ambient module declaration declares an internal or external module.
AmbientModuleDeclaration:
module
AmbientModuleIdentification
{
AmbientModuleBody
}
AmbientModuleIdentification:
IdentifierPath
StringLiteral
AmbientModuleBody:
AmbientElements
op
t
91
AmbientElements:
AmbientElement
AmbientElements AmbientElement
AmbientElement:
export
opt
AmbientVariableDeclaration
export
opt
AmbientFunctionDeclaration
export
opt
AmbientClassDeclaration
export
opt
InterfaceDeclaration
export
opt
AmbientModuleDeclaration
ImportDeclaration
An
AmbientModuleIdentification
with a
StringLiteral
declares an external module. This type of declaration
is permitted only in the global module. The
StringLiteral
must specify a top
-
level external module name.
Relative external module names are not permitted.
An
ImportDeclaration
in an
AmbientModuleDeclaration
for an external module may reference other
external modules only through top
-
level external module names. Relative external module names are not
permitted.
An
AmbientElement
declared an internal or external module must specify an export modifier (unless i
t is
an
ImportDeclaration
). Conversely, an
AmbientElement
declared in the global module cannot specify an
export modifier.
10.2
Declaration Source Files
Declaration source files (files with a ‘.d.ts’ extension) are restricted to contain ambient declarations onl
y.
Declaration source files can be used to declare the static type information associated with existing
JavaScript code in an adjunct manner.
DeclarationSourceFile:
AmbientElements
opt
A
DeclarationSourceFile
that contains no import or export declarations
contributes to the global module.
A
DeclarationSourceFile
that contains at least one import or export declaration is considered a separate
external module.