TypeScript
Language
Specification
Version
0.9
May
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.
Table of
Contents
2.2 Namespaces and Named Types
3.8.1 Type and Member Identity
3.8.3 Assignment Compatibility
4.9.1 Standard Function Expressions
4.9.2 Arrow Function Expressions
4.9.3 Contextually Typed Function Expressions
4.12.2 Type Argument Inference
4.14.1 The ++ and -- operators
4.14.2 The +, –, and ~ operators
4.15.1 The *, /, %, –, <<, >>,
>>>, &, ^, and | operators
4.15.3 The <, >, <=, >=, ==, !=, ===, and !==
operators
4.15.4 The instanceof operator
4.18 Contextually Typed Expressions
7.3 Interfaces
Extending Classes
8.1.1 Class Heritage Specification
8.2.1 Instance and Static Members
8.2.3 Inheritance and Overriding
8.2.5 Constructor Function Types
8.4.1 Member Variable Declarations
8.4.2 Member Function Declarations
8.4.3 Member Accessor Declarations
8.5.1 Classes Without Extends Clauses
8.5.2 Classes With Extends Clauses
11 Source Files and External Modules
11.1.1 Source Files Dependencies
11.2.2 External Import Declarations
12.1.1 Ambient Variable Declarations
12.1.2 Ambient Function Declarations
12.1.3 Ambient Class Declarations
12.1.4 Ambient Enum Declarations
12.1.5 Ambient Module Declarations
12.1.6 Ambient External Module Declarations
A.9 Programs and External Modules
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 software 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 programmers 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 matches 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 upon 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 generation 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 TypeScript 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 programmers 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 example, 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";
}
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.
In 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({}); // Error
f("hello"); // Ok
This optional type annotation on the parameter ‘s’ lets the TypeScript type checker know that the programmer expects parameter ‘s’ to be of type ‘string’. Within 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 object, 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.
An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable. For example, by default the TypeScript compiler will print an error for uses of undefined variables. To add some of the common variables defined by browsers, a TypeScript programmer can use ambient declarations. The following example declares the ‘document’ object supplied by browsers. Because the declaration does not specify a type, the type ‘any’ is inferred. The type ‘any’ means that a tool can assume nothing about the shape or behavior of the document object. Some of the examples below will illustrate how programmers can use types to further characterize the expected behavior of an object.
declare var document;
document.title = "Hello"; // Ok because
document has been declared
In the case of ‘document’, the TypeScript compiler automatically supplies a declaration, because TypeScript by default includes a file ‘lib.d.ts’ that provides interface declarations for the built-in JavaScript library as well as the Document Object Model.
The TypeScript compiler does not include by default an interface for jQuery, so to use jQuery, a programmer could supply a declaration such as:
declare var $;
Section 1.3 provides a more extensive example of how a programmer can add type information for jQuery and other libraries.
 They enable function definitions to create closures: functions that capture information from the lexical scope surrounding the function’s definition. Closures are currently JavaScript’s only way of enforcing data encapsulation. By capturing and using environment variables, a closure can retain information that cannot be accessed from outside the closure. JavaScript programmers often use closures to express event handlers and other asynchronous callbacks, in which another software component, such as the DOM, will call back into JavaScript through a handler function.
TypeScript function types make it possible for programmers to express the expected signature of a function. A function signature is a sequence of parameter types plus a return type. The following example uses function types to express the callback signature requirements of an asynchronous voting mechanism.
function vote(candidate: string,
callback: (result: string)
=> any)
{
// ...
}
vote("BigPig",
function(result:
string) {
if
(result === "BigPig")
{
// ...
}
}
);
In this example, the second parameter to ‘vote’ has the function type
(result: string) => any
which means the second parameter is a function returning type ‘any’ that has a single parameter of type ‘string’ named ‘result’.
Section 3.7.2 provides additional information about function types.
TypeScript programmers use object types to declare their expectations of object behavior. The following code uses an object type literal to specify the return type of the ‘MakePoint’ function.
var MakePoint: () => {
x: number; y: number;
};
Programmers can give names to object types; we call named object types interfaces. For example, in the following code, an interface declares one required field (name) and one optional field (favoriteColor).
interface Friend {
name: string;
favoriteColor?: string;
}
function add(friend: Friend) {
var name =
friend.name;
}
add({ name: "Fred"
}); // Ok
add({ favoriteColor: "blue" }); // Error, name
required
add({ name: "Jill",
favoriteColor: "green"
}); // Ok
TypeScript object types model the diversity of behaviors that a JavaScript object can exhibit. For example, the jQuery library defines an object, ‘$’, that has methods, such as ‘get’ (which sends an Ajax message), and fields, such as ‘browser’ (which gives browser vendor information). However, jQuery clients can also call ‘$’ as a function. The behavior of this function depends on the type of parameters passed to the function.
The following code fragment captures a small subset of jQuery behavior, just enough to use jQuery in a simple way.
interface JQuery {
text(content: string);
}
interface
JQueryStatic {
get(url: string,
callback: (data: string)
=> any);
(query: string): JQuery;
}
declare var $: JQueryStatic;
$.get("http://mysite.org/divContent",
function (data: string) {
$("div").text(data);
}
);
The ‘JQueryStatic’ interface references another interface: ‘JQuery’. This interface represents a collection of one or more DOM elements. The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the ‘text’ method. The ‘JQueryStatic’ interface also contains a method, ‘get’, that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response.
Finally, the ‘JQueryStatic’ interface contains a bare function signature
(query: string): JQuery;
The bare signature indicates that instances of the interface are callable. This example illustrates that TypeScript function types are just special cases of TypeScript object types. Specifically, function types are object types that contain only a call signature, but no properties. For this reason we can write any function type as an object type literal. The following example uses both forms to describe the same type.
var f: { (): string; };
var sameType: () => string = f; // Ok
var nope: () => number = sameType; // Error: type mismatch
We mentioned above that the ‘$’ function behaves differently depending on the type of its parameter. So far, our jQuery typing only captures one of these behaviors: return an object of type ‘JQuery’ when passed a string. To specify multiple behaviors, TypeScript supports overloading of function signatures in object types. For example, we can add an additional call signature to the ‘JQueryStatic’ interface.
(ready: () => any): any;
This signature denotes that a function may be passed as the parameter of the ‘$’ function. When a function is passed to ‘$’, the jQuery library will invoke that function when a DOM document is ready. Because TypeScript supports overloading, tools can use TypeScript to show all available function signatures with their documentation tips and to give the correct documentation once a function has been called with a particular signature.
A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot.
Section 3.3 provides additional information about object types.
Object types are compared structurally. For example, in the code fragment below, class ‘CPoint’ matches interface ‘Point’ because ‘CPoint’ has all of the required members of ‘Point’. A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility. The example also illustrates that an object type can match the type inferred from an object literal, as long as the object literal supplies all of the required members.
interface Point {
x: number;
y: number;
}
function getX(p: Point) {
return p.x;
}
class CPoint {
constructor (public x: number, public y: number) { }
}
getX(new CPoint(0, 0)); // Ok, fields match
getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
getX({ x: 0 }); // Error: supplied parameter does not match
See Section 3.8 for more information about type comparisons.
Ordinarily, TypeScript type inference proceeds “bottom-up”: from the leaves of an expression tree to its root. In the following example, TypeScript infers ‘number’ as the return type of the function ‘mul’ by flowing type information bottom up in the return expression.
function mul(a: number, b: number) {
return a * b;
}
For variables and parameters without a type annotation or a default value, TypeScript infers type ‘any’, ensuring that compilers do not need non-local information about a function’s call sites to infer the function’s return type. Generally, this bottom-up approach provides programmers with a clear intuition about the flow of type information.
However, in some limited contexts, inference proceeds “top-down” from the context of an expression. Where this happens, it is called contextual typing. Contextual typing helps tools provide excellent information when a programmer is using a type but may not know all of the details of the type. For example, in the jQuery example, above, the programmer supplies a function expression as the second parameter to the ‘get’ method. During typing of that expression, tools can assume that the type of the function expression is as given in the ‘get’ signature and can provide a template that includes parameter names and types.
$.get("http://mysite.org/divContent",
function (data)
{
$("div").text(data); // TypeScript
infers data is a string
}
);
Contextual typing is also useful for writing out object literals. As the programmer types the object literal, the contextual type provides information that enables tools to provide completion for object member names.
Section 4.18 provides additional information about contextually typed expressions.
JavaScript practice has at least two common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as ‘prototype.js’ are typical of this practice.
This section and the module section below will show how TypeScript emits consistent, idiomatic JavaScript code to implement classes and modules that are closely aligned with the current ES6 proposal. The goal of TypeScript’s translation is to emit exactly what a programmer would type when implementing a class or module unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We’ll start with a simple BankAccount class.
class BankAccount {
balance = 0;
deposit(credit: number) {
this.balance
+= credit;
return
this.balance;
}
}
This class generates the following JavaScript code.
var BankAccount = (function () {
function BankAccount()
{
this.balance
= 0;
}
BankAccount.prototype.deposit = function(credit) {
this.balance
+= credit;
return
this.balance;
};
return
BankAccount;
})();
This TypeScript class declaration creates a variable named ‘BankAccount’ whose value is the constructor function for ‘BankAccount’ instances. This declaration also creates an instance type of the same name. If we were to write this type as an interface it would look like the following.
interface BankAccount {
balance: number;
deposit(credit: number): number;
}
If we were to write out the function type declaration for the ‘BankAccount’ constructor variable, it would have the following form.
var BankAccount: new() => BankAccount;
The function signature is prefixed with the keyword ‘new’ indicating that the ‘BankAccount’ function must be called as a constructor. It is possible for a function’s type to have both call and constructor signatures. For example, the type of the built-in JavaScript Date object includes both kinds of signatures.
If we want to start our bank account with an initial balance, we can add to the ‘BankAccount’ class a constructor declaration.
class BankAccount {
balance: number;
constructor(initially:
number) {
this.balance
= initially;
}
deposit(credit: number) {
this.balance
+= credit;
return
this.balance;
}
}
This version of the ‘BankAccount’ class requires us to introduce a constructor parameter and then assign it to the ‘balance’ field. To simplify this common case, TypeScript accepts the following shorthand syntax.
class BankAccount {
constructor(public balance: number) {
}
deposit(credit: number) {
this.balance
+= credit;
return
this.balance;
}
}
The ‘public’ keyword denotes that the constructor parameter is to be retained as a field. Public is the default visibility for class members, but a programmer can also specify private visibility for a class member. Private visibility is a design-time construct; it is enforced during static type checking but does not imply any runtime enforcement.
TypeScript classes also support inheritance, as in the following example.
class CheckingAccount extends BankAccount {
constructor(balance: number) {
super(balance);
}
writeCheck(debit: number) {
this.balance -= debit;
}
}
In this example, the class ‘CheckingAccount’ derives from class ‘BankAccount’. The constructor for ‘CheckingAccount’ calls the constructor for class ‘BankAccount’ using the ‘super’ keyword. In the emitted JavaScript code, the prototype of ‘CheckingAccount’ will chain to the prototype of ‘BankingAccount’.
TypeScript classes may also specify static members. Static class members become properties of the class constructor.
Section 8 provides additional information about classes.
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 that component’s implementation. 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 properties are accessible at runtime. Future versions of JavaScript 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 methods using closure variables. The module pattern is a natural way to provide organizational structure and dynamic loading options by drawing a boundary around a software component. 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 module closure is a function that encapsulates the module’s implementation, in this case the variable ‘key’ and the function ‘sendMessage’. The module object contains the exported variables and functions of the module. Simple modules may create and return the 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 module 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 provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting modules and classes within an outer module.
The following example shows the definition and use of a simple module.
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 write
interface M {
f(): string;
}
var M: M;
The interface ‘M’ summarizes the externally visible 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 variable names do not conflict: each lexical scope contains a variable declaration space and type declaration space (see Section 2.3 for more details).
Module ‘M’ is an example 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 variable ‘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 code whose module closure and module object implementation vary according to the specified dynamic loading system, for example, the Asynchronous Module Definition system.
The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the ECMAScript Language Specification (specifically, the ECMA-262 Standard, 5th 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 covered by the ECMAScript specification.
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 ( ArgumentListopt )
super . IdentifierName
The ‘( Modified )’ annotation indicates that an existing grammar production is being replaced, and the ‘…’ references the contents of the original grammar production.
TypeScript supports named types that can be organized in hierarchical namespaces. Namespaces are introduced by module declarations and named types are introduced by class, interface, and enum declarations. Named types are denoted by qualified names that extend from some root module (possibly the global module) to the point of their declaration. The example
module X {
export module Y {
export
interface
Z { }
}
export interface Y { }
}
declares two interface types with the qualified names ‘X.Y.Z’ and ‘X.Y’ relative to the root module in which ‘X’ is declared.
In a qualified type name all identifiers but the last one refer to namespaces and the last identifier refers to a named type. Named type and namespace names are in separate declaration spaces and it is therefore possible for a named type and a namespace to have the same name, as in the example above.
The hierarchy formed by namespace and named type names partially mirrors that formed by module instances and members. The example
module A {
export module B {
export
class C { }
}
}
introduces a named type with the qualified name ‘A.B.C’ and also introduces a constructor function that can be accessed using the expression ‘A.B.C’. Thus, in the example
var c: A.B.C = new A.B.C();
the two occurrences of ‘A.B.C’ in fact refer to different entities. It is the context of the occurrences that determines whether ‘A.B.C’ is processed as a type name or an expression.
Declarations introduce names in the declaration spaces to which they belong. It is an error to have two names with same spelling in the same declaration space. Declaration spaces exist as follows:
Š The global module and each external or internal module has a declaration space for variables (including functions, modules, class constructor functions, and enum objects), a declaration space for named types (classes, interfaces, and enums), and a declaration space for namespaces (containers of named types). Every declaration (whether local or exported) in a module contributes to one or more of these declaration spaces.
Š Each external or internal module has a declaration space for exported members, a declaration space for exported named types, and a declaration space for exported namespaces. All export declarations in the module contribute to these declaration spaces. Each internal module’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 class declaration has a declaration space for instance members, a declaration space for static members, and a declaration space for type parameters.
Š Each interface declaration has a declaration space for members and a declaration space for type parameters. An interface’s declaration space is shared with other interfaces that have the same root module and the same qualified name starting from that root module.
Š Each enum declaration has a declaration space for its enum members. An enum’s declaration space is shared with other enums that have the same root module and the same qualified name starting from that root module.
Š Each function declaration (including constructor, member function, and member accessor declarations) and each function expression has a declaration space for variables (parameters, local variables, and local functions) and a declaration space for type parameters.
Š Each object literal has a declaration space for its properties.
Š Each object type literal has a declaration space for its members.
Top-level declarations in a source file with no top-level import or export declarations belong to the global module. Top-level declarations in a source file with one or more top-level import or export declarations belong to the external module represented by that source file.
An internal module declaration contributes a namespace name (representing a container of types) and possibly a member name (representing the module instance) to the containing module. A class declaration contributes both a member name (representing the constructor function) and a type name (representing the class type) to the containing module. An interface declaration contributes a type name to the containing module. An enum declaration contributes both a member name (representing the enum object) and a type name (representing the enum type) to the containing module. Any other declaration contributes a member name to the declaration space to which it belongs.
The parent module of an entity is defined as follows:
Š The parent module of an entity declared in an internal module is that internal module.
Š The parent module of an entity declared in an external module is that external module.
Š The parent module of an entity declared in the global module is the global module.
Š The parent module of an external module is the global module.
The root module of an entity is defined as follows:
Š The root module of a non-exported entity is the entity’s parent module.
Š The root module of an exported entity is the root module of the entity’s parent module.
Intuitively, the root module of an entity is the outermost module body from within which the entity is reachable.
Interfaces, enums, and internal modules are “open ended,” meaning that interface, enum, and internal module declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections 7.2, 9.3, and 10.5.
Namespace, type, and member names exist in separate declaration spaces. Furthermore, declarations of non-instantiated modules (modules that contain only interfaces or modules at all levels of nesting) do not introduce a member name in their containing declaration space. This means that the following is permitted, provided module ‘X’ contains only interface or module declarations at all levels of nesting:
module M {
module X { ...
} // Namespace
interface X { ...
} // Type
var X;
// Member
}
If module ‘X’ above was an instantiated module (section 10.1) it would cause a member ‘X’ to be introduced in ‘M’. This member would conflict with the variable ‘X’ and thus cause an error.
Instance and static members in a class are likewise in separate declaration spaces. Thus the following is permitted:
class C {
x: number; // Instance member
static x:
string; // Static member
}
The scope of a name is the region of program text within which it is possible to refer to the entity declared by that name without qualification of the name. The scope of a name depends on the context in which the name is declared. The contexts are listed below in order from outermost to innermost:
Š The scope of an entity declared in the global module is the entire program text.
Š The scope of an entity declared in an external module is the source file of that external module.
Š The scope of an exported entity declared in an internal module is the body of that module and every internal module with the same root and the same qualified name relative to that root.
Š The scope of a non-exported entity declared within an internal module declaration is the body of that internal module declaration.
Š The scope of a type parameter declared in a class or interface declaration is that entire declaration, including constraints, extends clause, implements clause, and declaration body, but not including static member declarations.
Š The scope of a type parameter declared in a call or construct signature is that entire signature declaration, including constraints, parameter list, and return type. If the signature is part of a function implementation, the scope includes the function body.
Š The scope of a parameter, local variable, or local function declared within a function declaration (including a constructor, member function, or member accessor declaration) or function expression is the body of that function declaration or function expression.
Scopes may overlap, for example through nesting of modules and functions. When the scopes of two entities with the same name overlap, the entity with the innermost declaration takes precedence and access to the outer entity is either not possible or only possible by qualifying its name.
When an identifier is resolved as a TypeName (section 3.6.2), only classes, interfaces, enums, and type parameters are considered and other entities in scope are ignored.
When an identifier is resolved as a ModuleName (section 3.6.2), only modules are considered and other entities in scope are ignored.
When an identifier is resolved as
a PrimaryExpression (section 4.3), only instantiated modules (section 10.1), classes, enums, functions, variables, and parameters are considered
and other entities in scope are ignored.
Note that class and enum members
are never directly in scope—they can only be accessed by applying the dot
(‘.’) operator to a class instance or enum object. This even includes members
of the current instance in a constructor or member function, which are accessed
by applying the dot operator to this.
As the rules above imply, locally
declared entities in an internal module are closer in scope than exported
entities declared in other module declarations for the same internal module.
For example:
var x = 1;
module M {
export var x = 2;
console.log(x); // 2
}
module M {
console.log(x); // 2
}
module M {
var x = 3;
console.log(x); // 3
}
TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript’s static compile-time type system closely models the dynamic run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript’s type analysis occurs entirely at compile-time and adds no run-time overhead to program execution.
All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.
The primitive types are the Number, Boolean, String, Void, Null, and Undefined types along with user defined enum types. The number, boolean, string, and void keywords reference the Number, Boolean, String, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only values of those types can be referenced, using the null and undefined literals.
The object types are all class, interface, array, and literal types. Class and interface types are introduced through class and interface declarations and are referenced by the name given to them in their declarations. Class and interface types may be generic types which have one or more type parameters. Literal types are written as object, array, function, or constructor type literals and are used to compose new types from other types.
Declarations of modules, classes, properties, functions, variables and other language entities associate types with those entities. The mechanism by which a type is formed and associated with a language entity depends on the particular kind of entity. For example, a module declaration associates the module with an anonymous type containing a set of properties corresponding to the exported variables and functions in the module, and a function declaration associates the function with an anonymous type containing a call signature corresponding to the parameters and return type of the function. Types can be associated with variables through explicit type annotations, such as
var x: number;
or through implicit type inference, as in
var x = 1;
which infers the type of ‘x’ to be the Number primitive type because that is the type of the value used to initialize ‘x’.
The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.
The any keyword references the Any type. In general, in places where a type is not explicitly provided and TypeScript cannot infer one, the Any type is assumed.
The Any type is a supertype of all types.
Some examples:
var
x: any;
// Explicitly
typed
var
y;
// Same
as y: any
var z: {
a; b; };
// Same
as z: { a: any; b: any; }
function
f(x) {
// Same
as f(x: any): void
console.log(x);
}
The primitive types are the Number, Boolean, String, Void, Null, and Undefined types and all user defined enum types.
The Number primitive type corresponds to the similarly named JavaScript primitive type and represents double-precision 64-bit format IEEE 754 floating point values.
The number keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), the Number primitive type behaves as an object type with the same properties as the global interface type ‘Number’.
Some examples:
var
x: number;
//
Explicitly typed
var y = 0;
// Same
as y: number = 0
var z = 123.456; // Same as z: number =
123.456
var s =
z.toFixed(2); // Property of Number interface
The Boolean primitive type corresponds to the similarly named JavaScript primitive type and represents logical values that are either true or false.
The boolean keyword references the Boolean primitive type and the true and false literals reference the two Boolean truth values.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), the Boolean primitive type behaves as an object type with the same properties as the global interface type ‘Boolean’.
Some examples:
var
b: boolean;
//
Explicitly typed
var yes = true;
// Same
as yes: boolean = true
var no = false;
// Same
as no: boolean = false
The String primitive type corresponds to the similarly named JavaScript primitive type and represents sequences of characters stored as Unicode UTF-16 code units.
The string keyword references the String primitive type and string literals may be used to write values of the String primitive type.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), the String primitive type behaves as an object type with the same properties as the global interface type ‘String’.
Some examples:
var
s: string;
//
Explicitly typed
var empty
= "";
// Same
as empty: string = ""
var abc = 'abc'; // Same as abc: string
= "abc"
var c =
abc.charAt(2); // Property of String interface
The Void type, referenced by the void keyword, represents the absence of a value and is used as the return type of functions with no return value.
The only possible values for the Void type are null and undefined. The Void type is a subtype of the Any type and a supertype of the Null and Undefined types, but otherwise Void is unrelated to all other types.
NOTE: We might
consider disallowing declaring variables of type Void as they serve no useful purpose.
However, because Void is permitted as a type argument to a generic type or function
it is not feasible to disallow Void properties or parameters.
The Null type corresponds to the similarly named JavaScript primitive type and is the type of the null literal.
The null literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself.
The Null type is a subtype of all types, except the Undefined type. This means that null is considered a valid value for all primitive types, object types, and type parameters, including even the Number and Boolean primitive types.
Some examples:
var
n: number
= null; // Primitives can be null
var x = null;
// Same
as x: any = null
var e:
Null;
// Error,
can't reference Null type
The Undefined type corresponds to the similarly named JavaScript primitive type and is the type of the undefined literal.
The undefined literal denotes the value given to all uninitialized variables and is the one and only value of the Undefined type. It is not possible to directly reference the Undefined type itself.
The undefined type is a subtype of all types. This means that undefined is considered a valid value for all primitive types, object types, and type parameters.
Some examples:
var
n: number;
// Same
as n: number = undefined
var x =
undefined; // Same as x: any =
undefined
var e:
Undefined;
// Error,
can't reference Undefined type
Enum types are distinct user defined subtypes of the Number primitive type. Enum types are declared using enum declarations (section 9.1) and referenced using type references (section 3.6.2).
Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other.
Specialized signatures (section <IP_ADDRESS>) permit string literals to be used as types in parameter type annotations. String literal types are permitted only in that context and nowhere else.
All string literal types are subtypes of the String primitive type.
The object types include references to class and interface types as well as anonymous object types created by a number of constructs such as object literals, function declarations, and module declarations. Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members.
Type references (section 3.6.2) to class and interface types are classified as object types. Type references to generic class and interface types include type arguments that are substituted for the type parameters of the class or interface to produce an actual object type.
Array types represent JavaScript arrays. Array types are type references (section 3.6.2) created from the generic interface type ‘Array’ in the global module. Array type literals (section 3.6.3) provide a shorthand notation for creating such references.
Array literals (section 4.6) may be used to create values of array types.
Several constructs in the TypeScript language introduce new anonymous object types:
Š Function and constructor type literals (section 3.6.3).
Š Object type literals (section 3.7).
Š Object literals (section 4.5).
Š Function expressions (section 4.9) and function declarations (6.1).
Š Constructor function types created by class declarations (section 8.2.5).
Š Module instance types created by module declarations (section 10.3).
Every object type is composed from zero or more of the following kinds of members:
Š Properties, which define the names and types of the properties of objects of the given type. Property names are unique within their type.
Š Call signatures, which define the possible parameter lists and return types associated with applying call operations to objects of the given type.
Š Construct signatures, which define the possible parameter lists and return types associated with applying the new operator to objects of the given type.
Š Index signatures, which define type constraints for properties in the given type.
Properties are either public or private and are either required or optional:
Š Properties in a class declaration may be designated public or private, while properties declared in other contexts are always considered public. Private members are only accessible within the class body containing their declaration, as described in section 8.2.2, and private properties match only themselves in subtype and assignment compatibility checks, as described in section 3.8.
Š Properties in an object type literal or interface declaration may be designated required or optional, while properties declared in other contexts are always considered required. Properties that are optional in the target type of an assignment may be omitted from source objects, as described in section 3.8.3.
Call and construct signatures may be specialized (section <IP_ADDRESS>) by including parameters with string literal types. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), object types appear to have certain additional members:
Š Every object type appears to have the members of the global interface type ‘Object’ unless those members are hidden by members in the object type.
Š An object type with one or more call or construct signatures appears to have the members of the global interface type ‘Function’ unless those members are hidden by members in the object type.
Object type members hide ‘Object’ or ‘Function’ interface members in the following manner:
Š A property hides an ‘Object’ or ‘Function’ property with the same name.
Š A call signature hides an ‘Object’ or ‘Function’ call signature with the same number of parameters and identical parameter types in the respective positions.
Š A construct signature hides an ‘Object’ or ‘Function’ construct signature with the same number of parameters and identical parameter types in the respective positions.
Š An index signature hides an ‘Object’ or ‘Function’ index signature with the same parameter type.
In effect, object types are subtypes of the ‘Object’ or ‘Function’ interface unless the object types define members that are incompatible with those of the ‘Object’ or ‘Function’ interface—which, for example, occurs if an object type defines a property with the same name as a property in the ‘Object’ or ‘Function’ interface but with a type that isn’t a subtype of that in the ‘Object’ or ‘Function’ interface.
Some examples:
var
o: Object = { x: 10,
y: 20 };
// Ok
var f:
Function = (x: number)
=> x * x; // Ok
var err: Object
= { toString: 0
};
// Error,
incompatible toString
A type parameter represents an actual type that the parameter is bound to in a generic type reference or a generic function call. Type parameters have constraints that establish upper bounds for their actual type arguments.
Since a type parameter represents a multitude of different type arguments, type parameters have certain restrictions compared to other types. In particular, a type parameter cannot be used as a base class or interface.
For purposes of determining type relationships (section 3.8), type parameters appear to be subtypes of the constraint specified in their declaration (or subtypes of ‘Object’ when no constraint was specified). Likewise, for purposes of accessing properties (section 4.10), type parameters appear to have the members of their declared constraint, but no other members.
Class, interface, and enum types are named types that are introduced through class declarations (section 8.1), interface declarations (section 7.1), and enum declarations (9.1). Class and interface types may have type parameters and are then called generic types. Conversely, named types without type parameters are called non-generic types.
Interface declarations only introduce named types, whereas class declarations introduce named types and constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can’t declare optional members and interfaces can’t declare private members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations.
Named types are referenced through type references (section 3.6.2) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type.
Named types are technically not types, only references to named types are. This distinction is particularly evident with generic types: Generic types are “templates” from which multiple actual types can be created by writing type references that supply type arguments to substitute in place of the generic type’s type parameters. Only once this substitution takes place does a generic type denote an actual type.
Since TypeScript has a structural type system, a type created from a reference to a generic type is indistinguishable from an equivalent manually written expansion. For example, given the declaration
interface Pair<T1, T2> { first: T1;
second: T2; }
the type
reference
Pair<string,
Entity>
is
indistinguishable from the type
{ first:
string; second: Entity; }
Class, interface, and function declarations may optionally include lists of type parameters enclosed in < and > brackets. Type parameters are also permitted in call signatures of object, function, and constructor type literals.
TypeParameters:
< TypeParameterList >
TypeParameterList:
TypeParameter
TypeParameterList , TypeParameter
TypeParameter:
Identifier Constraintopt
Constraint:
extends TypeReference
Type parameter names must be unique. A compile-time error occurs if two or more type parameters in the same TypeParameterList have the same name.
The scope of a type parameter extends over the entire declaration with which the type parameter list is associated, the only exception being static member declarations in classes.
Each type parameter has an associated type parameter constraint that establishes an upper bound for type arguments: A type argument for a given type parameter must be assignable to the type specified in the type parameter constraint. The type given in a type parameter constraint declaration must be an object type or a type parameter (i.e. a constraint cannot be the Any type or a primitive type). Omitting a constraint corresponds to specifying the global interface type ‘Object’.
Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter.
Generic types are permitted to directly or indirectly reference themselves in a recursive fashion as long as such references do not generate an infinite series of new types. Specifically, within a generic type G < T1 , T2 , … , Tn > and the types referenced by it, it is an error to reference G with a type argument that wraps any of G’s own type parameters (i.e. a type argument that wraps any Tx). A type parameter is said to be wrapped by a particular type when it is referenced, directly or indirectly, within that type.
Consider the following example:
interface
List<T> {
data: T;
next: List<T>;
owner: List<List<T>>; // Error, recursive reference with wrapped T
}
In the example the ‘owner’ property creates an infinite series of new types that wrap a ‘List<T>’ around each previous ‘List<T>’. Such generative recursion is prohibited by the rule above.
Note that it would be perfectly fine for the ‘owner’ property to have type ‘List<List<Object>>’ or any other type with a nested reference to ‘List’ that doesn’t reference ‘T’.
TODO: The restriction
on generative recursion is likely to be removed.
Each named type has an associated actual type known as the instance type. For a non-generic type, the instance type is simply a type reference to the non-generic type. For a generic type, the instance type is formed by creating a type reference from the generic type where each of the supplied type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the generic type. Within the constructor and member functions of a class, the type of this is the instance type of the class.
The following example illustrates the concept of an instance type:
class
G<T> {
// Introduce type parameter T
self: G<T>;
// Use T as type argument to form instance type
f() {
this.self
= this; // self and this are
both of type G<T>
}
}
Types are specified either by referencing their keyword or name or by writing type literals which compose other types into new types.
Type:
PredefinedType
TypeReference
TypeLiteral
The any, number, boolean, string, and void keywords reference the Any type and the Number, Boolean, String, and Void primitive types respectively.
PredefinedType:
any
number
boolean
string
void
The predefined type keywords are reserved and cannot be used as names of user defined types.
A type reference references a named type or type parameter through its name and an optional type argument list.
TypeReference:
TypeName TypeArgumentsopt
TypeName:
Identifier
ModuleName . Identifier
ModuleName:
Identifier
ModuleName . Identifier
A TypeReference consists of a TypeName that a references a named type or type parameter. A reference to a generic type may optionally be followed by a list of TypeArguments.
Resolution of a TypeName consisting of a single identifier is described in section 2.4.
Resolution of a TypeName 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 module contains an exported named type N, then M.N refers to that member. Otherwise, M.N is undefined.
Resolution of a ModuleName consisting of a single identifier is described in section 2.4.
Resolution of a ModuleName 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 module contains an exported module member N, then M.N refers to that member. Otherwise, M.N is undefined.
A type reference to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas.
TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument
TypeArgumentList , TypeArgument
TypeArgument:
Type
A type reference to a generic type is required to specify exactly one type argument for each type parameter of the referenced generic type. Each type argument must be assignable to (section 3.8.3) the constraint of the corresponding type parameter or otherwise an error occurs. An example:
interface A { a: string; }
interface B extends A { b: string; }
interface C extends B { c: string; }
interface
G<T, U extends
B> {
x: T;
y: U;
}
var
v1: G<A, C>; // Ok
var v2:
G<{ a: string
}, C>; // Ok, equivalent to
G<A, C>
var v3: G<A,
A>; // Error, A not valid
argument for U
var
v4: G<G<A, B>, C>; // Ok
var v5: G<any, any>;
// Ok
var v6:
G<any>;
// Error,
wrong number of arguments
var v7: G;
// Error, no arguments
A type argument is simply a Type and may itself be a type reference to a generic type, as demonstrated by ‘v4’ in the example above.
A type reference to a generic type G designates a type wherein all occurrences of G’s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of ‘v1’ above is equivalent to:
var
v1: {
x: { a: string; }
y: { a: string; b: string; c: string };
};
Type literals compose other types into new anonymous types.
TypeLiteral:
ObjectType
ArrayType
FunctionType
ConstructorType
ArrayType:
Type [ ]
FunctionType:
TypeParametersopt ( ParameterListopt ) => Type
ConstructorType:
new TypeParametersopt ( ParameterListopt ) => Type
Object type literals are the primary form of type literals and are described in section 3.7. Array, function, and constructor type literals are simply shorthand notations for other types:
|
Type literal |
Equivalent form |
|
T [ ] |
Array < T > |
|
< TParams > ( Params ) => Result |
{ < TParams > ( Params ) : Result } |
|
new < TParams > ( Params ) => Result |
{ new < TParams > ( Params ) : Result } |
As the table above illustrates, an array type literal is shorthand for a reference to the generic interface type ‘Array’ in the global module, a function type literal is shorthand for an object type containing a single call signature, and a constructor type literal is shorthand for an object type containing a single construct signature. Note that function and constructor types with multiple call or construct signatures cannot be written as function or constructor type literals but must instead be written as object type literals.
An 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 literals can be given names using interface declarations but are otherwise anonymous.
ObjectType:
{ TypeBodyopt }
TypeBody:
TypeMemberList ;opt
TypeMemberList:
TypeMember
TypeMemberList ; TypeMember
TypeMember:
PropertySignature
CallSignature
ConstructSignature
IndexSignature
MethodSignature
The members of an object type literal are specified as a combination of property, call, construct, index, and method signatures. The signatures are separated by semicolons and enclosed in curly braces.
A property signature declares the name and type of a property member.
PropertySignature:
PropertyName ?opt TypeAnnotationopt
PropertyName:
IdentifierName
StringLiteral
NumericLiteral
The PropertyName production, reproduced above from the ECMAScript grammar, permits a property name to be any identifier (including a reserved word), a string literal, or a numeric literal. String literals can be used to give properties names that are not valid identifiers, such as names containing blanks. Numeric literal property names are equivalent to string literal property names with the string representation of the numeric literal, as defined in the ECMAScript specification.
The PropertyName of a property signature must be unique within its containing type. If the property name is followed by a question mark, the property is optional. Otherwise, the property is required.
If a property signature omits a TypeAnnotation, the Any type is assumed.
A call signature defines the type parameters, parameter list, and return type associated with applying a call operation (section 4.12) to an instance of the containing type. A type may overload call operations by defining multiple different call signatures.
CallSignature:
TypeParametersopt ( ParameterListopt ) TypeAnnotationopt
A call signature that includes TypeParameters (section 3.5.1) is called a generic call signature. Conversely, a call signature with no TypeParameters is called a non-generic call signature.
As well as being members of object type literals, call
signatures occur in method signatures (section 3.7.5),
function expressions (section 4.9),
and function declarations (section 6.1).
An object type containing call signatures is said to be a function type.
It is an error for a type to declare multiple call signatures that are considered identical (section 3.8.1) or differ only in their return types.
Type parameters in call signatures provide a mechanism for expressing the relationships of parameter and return types in call operations. For example, a signature might introduce a type parameter and use it as both a parameter type and a return type, in effect describing a function that returns a value of the same type as its argument.
The scope of a type parameter extends over the entire call signature in which the type parameter is introduced. Thus, type parameters may be referenced in type parameter constraints, parameter types, and return type annotations in their associated call signature.
Type arguments for call signature type parameters may be explicitly specified in a call operation or may, when possible, be inferred (section 4.12.2) from the types of the regular arguments in the call.
A signature’s parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter.
ParameterList:
RequiredParameterList
OptionalParameterList
RestParameter
RequiredParameterList , OptionalParameterList
RequiredParameterList , RestParameter
OptionalParameterList , RestParameter
RequiredParameterList , OptionalParameterList , RestParameter
RequiredParameterList:
RequiredParameter
RequiredParameterList , RequiredParameter
RequiredParameter:
PublicOrPrivateopt
Identifier
TypeAnnotationopt
Identifier : StringLiteral
PublicOrPrivate:
public
private
OptionalParameterList:
OptionalParameter
OptionalParameterList , OptionalParameter
OptionalParameter:
PublicOrPrivateopt
Identifier ? TypeAnnotationopt
PublicOrPrivateopt
Identifier
TypeAnnotationopt
Initialiser
RestParameter:
... Identifier TypeAnnotationopt
Parameter names must be unique. A compile-time error occurs if two or more parameters have the same name.
A parameter is permitted to include a public or private modifier only if it occurs in the parameter list of a ConstructorImplementation (section 8.3.1).
A parameter with a type annotation is considered to be of that type. A type annotation for a rest parameter must denote an array type.
A parameter with no type annotation or initializer is considered to be of type any, unless it is a rest parameter, in which case it is considered to be of type any[].
When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section <IP_ADDRESS>). Specialized signatures are not permitted in conjunction with a function body, i.e. the FunctionExpression, FunctionImplementation, MemberFunctionImplementation, and ConstructorImplementation grammar productions do not permit parameters with string literal types.
A parameter can be marked optional by following its name with a question mark (?) or by including an initializer. The form that includes an initializer is permitted only in conjunction with a function body, i.e. only in a FunctionExpression, FunctionImplementation, MemberFunctionImplementation, or ConstructorImplementation grammar production.
TODO: Rest parameters.
If present, a call signature’s return type annotation specifies the type of the value computed and returned by a call operation. A void return type annotation is used to indicate that a function has no return value.
When a call signature with no return type annotation occurs in a context without a function body, the return type is assumed to be the Any type.
When a call signature with no return type annotation occurs in a context that has a function body (specifically, a function implementation, a member function implementation, or a member accessor declaration), the return type is inferred from the function body as described in section 6.3.
When a parameter type annotation specifies a string literal type (section 3.2.8), the containing signature is considered a specialized signature. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. For example, the declaration
interface
Document {
createElement(tagName:
string):
HTMLElement;
createElement(tagName:
"div"):
HTMLDivElement;
createElement(tagName:
"span"):
HTMLSpanElement;
createElement(tagName:
"canvas"):
HTMLCanvasElement;
}
states that calls to ‘createElement’ with the string literals “div”, “span”, and “canvas” return values of type ‘HTMLDivElement’, ‘HTMLSpanElement’, and ‘HTMLCanvasElement’ respectively, and that calls with all other string expressions return values of type ‘HTMLElement’. Because string literal types are subtypes of the String primitive type, when a function call argument matches a parameter of a string literal type in a specialized signature, the overload resolution rules (section 4.12.1) give preference to that signature over a similar signature with a regular string parameter.
Every specialized call or construct signature in an object type must be a subtype of at least one non-specialized call or construct signature in the same object type. For example, the ‘createElement’ property in the example above is of a type that contains three specialized signatures, all of which are subtypes of the non-specialized signature in the type.
A construct signature defines the parameter list and return type associated with applying the new operator (section 4.11) to an instance of the containing type. A type may overload new operations by defining multiple construct signatures with different parameter lists.
ConstructSignature:
new TypeParametersopt ( ParameterListopt ) TypeAnnotationopt
The type parameters, parameter list, and return type of a construct signature are subject to the same rules as a call signature.
A type containing construct signatures is said to be a constructor type.
It is an error for a type to declare multiple construct signatures that are considered identical (section 3.8.1) or differ only by their return types.
An index signature defines a type constraint for properties in the containing type.
IndexSignature:
[ Identifier : string ] TypeAnnotation
[ Identifier : number ] TypeAnnotation
There are two kinds of index signatures:
Š String index signatures, specified using index type string, define type constraints for all properties and numeric index signatures in the containing type. Specifically, in a type with a string index signature of type T, all properties and numeric index signatures must have types that are subtypes of T.
Š Numeric index signatures, specified using index type number, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type T, all numerically named properties must have types that are subtypes of T.
A numerically named property is a property whose name is a valid numeric literal. Specifically, a property with a name N for which ToNumber(N) is not NaN, where ToNumber is the abstract operation defined in ECMAScript specification.
Index signatures affect the determination of the type that results from applying a bracket notation property access to an instance of the containing type, as described in section 4.10.
A method signature is shorthand for declaring a property of a function type.
MethodSignature:
PropertyName ?opt CallSignature
If the identifier is followed by a question mark, the property is optional. Otherwise, the property is required. Only object type literals and interfaces can declare optional properties.
A method signature of the form
PropName < TypeParamList > ( ParamList ) : ReturnType
is equivalent to the property declaration
PropName : { < TypeParamList > ( ParamList ) : ReturnType }
A literal type may overload a method by declaring multiple method signatures with the same name but differing parameter lists. Overloads must either all be required (question mark omitted) or all be optional (question mark included). A set of overloaded method signatures correspond to a declaration of a single property with a type composed from an equivalent set of call signatures. Specifically
PropName < TypeParamList1 > ( ParamList1 ) : ReturnType1 ;
PropName < TypeParamList2
> ( ParamList2 ) : ReturnType2 ;
…
PropName < TypeParamListn
> ( ParamListn ) : ReturnTypen ;
is equivalent to
PropName : {
< TypeParamList1 > ( ParamList1 ) : ReturnType1 ;
< TypeParamList2 > ( ParamList2 ) : ReturnType2 ;
…
< TypeParamListn > ( ParamListn ) : ReturnTypen ; }
In the following example of an object type
{
func1(x: number): number;
// Method signature
func2: (x: number) => number; // Function type literal
func3: { (x: number): number }; // Object
type literal
}
the properties ‘func1’, ‘func2’, and ‘func3’ are all of the same type, namely an object type with a single call signature taking a number and returning a number. Likewise, in the object type
{
func4(x: number): number;
func4(s: string): string;
func5: {
(x: number):
number;
(s: string):
string;
};
}
the properties ‘func4’ and ‘func5’ are of the same type, namely an object type with two call signatures taking and returning number and string respectively.
Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections.
For purposes of determining type relationships, all object types appear to have the members of the ‘Object’ interface unless those members are hidden by members with the same name in the object types, and object types with one or more call or construct signatures appear to have the members of the ‘Function’ interface unless those members are hidden by members with the same name in the object types.
For purposes of determining subtype, supertype, and assignment compatibility relationships, the Number, Boolean, and String primitive types are treated as object types with the same properties as the ‘Number’, ‘Boolean’, and ‘String’ interfaces respectively. Likewise, enum types are treated as object types with the same properties as the ‘Number’ interface.
All type parameters appear to have the members of their constraint (or the ‘Object’ interface if they have no constraint), but no other members.
Two types are considered identical when
Š they are the same primitive type,
Š they are the same type parameter, or
Š they are object types with identical sets of members.
Two members are considered identical when
Š they are public properties with identical names, optionality, and types,
Š they are private properties originating in the same declaration and having identical types,
Š they are identical call signatures,
Š they are identical construct signatures, or
Š they are index signatures of identical kind with identical types.
Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those type parameters pairwise identical, have identical type parameter constraints, identical number of parameters of identical kinds and types, and identical return types.
Note that, except for primitive types and classes with private members, it is structure, not naming, of types that determines identity. Also, note that parameter names are not significant when determining identity of signatures.
Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type
interface A { next: A; }
contains an infinitely nested sequence of ‘next’ properties. Types such as this are perfectly valid but require special treatment when determining type relationships. Specifically, when comparing references to two named types S and T for a given relationship (identity, subtype, or assignability), the relationship in question is assumed to be true for every directly or indirectly nested occurrence of references to the same S and T (where same means originating in the same declaration). For example, consider the identity relationship between ‘A’ above and ‘B’ below:
interface B { next: C; }
interface C { next: D; }
interface D { next: B; }
To determine whether ‘A’ and ‘B’ are identical, first the ‘next’ properties of type ‘A’ and ‘C’ are compared. That leads to comparing the ‘next’ properties of type ‘A’ and ‘D’, which leads to comparing the ‘next’ properties of type ‘A’ and ‘B’. Since ‘A’ and ‘B’ are already being compared this relationship is by definition true. That in turn causes the other comparisons to be true, and therefore the final result is true.
When this same technique is used to compare generic type references, two type references are considered the same when they originate in the same declaration and have identical type arguments. However, certain recursive generic patterns are prohibited, as explained in section 3.5.2.
Private properties match only if they originate in the same declaration and have identical types. Two distinct types might contain properties that originate in the same declaration if the types are separate parameterized references to the same generic class. In the example
class C<T> { private x: T; }
interface X { f(): string; }
interface Y { f(): string; }
var a: C<X>;
var b:
C<Y>;
the variables ‘a’ and ‘b’ are of identical types because the two type references to ‘C’ create types with a private member ‘x’ that originates in the same declaration, and because the two private ‘x’ members have types with identical sets of members once the type arguments ‘X’ and ‘Y’ are substituted.
Given a type S and a substitution type S’ where
Š when S is the primitive type Number, Boolean, or String, S’ is the global interface type ‘Number’, ‘Boolean’, or ‘String’,
Š when S is an enum type, S’ is the global interface type ‘Number’,
Š when S is a type parameter, S’ is the constraint of that type parameter,
Š otherwise, S’ is S,
S is a subtype of a type T, and T is a supertype of S, if one of the following is true:
Š S and T are identical types.
Š T is the Any type.
Š S is the Undefined type.
Š S is the Null type and T is not the Undefined type.
Š S is an enum type and T is the primitive type Number.
Š S is a string literal type and T is the primitive type String.
Š S’ and T are object types and, for each member M in T, one of the following is true:
o M is a public property and S’ contains a public property of the same name as M and a type that is a subtype of that of M.
o M is a private property and S’ contains a private property that originates in the same declaration as M and has a type that is a subtype of that of M.
o M is an optional property and S’ contains no property of the same name as M.
o M is a non-specialized call or construct signature and S’ contains a call or construct signature N where, when substituting ‘Object’ for all type parameters declared by M and N (if any),
§ the signatures are of the same kind (call or construct),
§ the number of non-optional parameters in N is less than or equal to that of M,
§ for parameter positions that are present in both signatures, each parameter type in N is a subtype or supertype of the corresponding parameter type in M,
§ the result type of M is Void, or the result type of N is a subtype of that of M.
o M is a string index signature of type U and S’ contains a string index signature of a type that is a subtype of U.
o M is a numeric index signature of type U and S’ contains a string or numeric index signature of a type that is a subtype of U.
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
Note that specialized call and construct signatures (section <IP_ADDRESS>) are not significant when determining subtype and supertype relationships.
Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls.
Given a type S and a substitution type S’ where
Š when S is the primitive type Number, Boolean, or String, S’ is the global interface type ‘Number’, ‘Boolean’, or ‘String’,
Š when S is an enum type, S’ is the global interface type ‘Number’,
Š when S is a type parameter, S’ is the constraint of that type parameter,
Š otherwise, S’ is S,
S is assignable to a type T, and T is assignable from S, if one of the following is true:
Š S and T are identical types.
Š S or T is the Any type.
Š S is the Undefined type.
Š S is the Null type and T is not the Undefined type.
Š S or T is an enum type and the other is the primitive type Number.
Š S’ and T are object types and, for each member M in T, one of the following is true:
o M is a public property and S’ contains a public property of the same name as M and a type that is assignable to that of M.
o M is a private property and S’ contains a private property that originates in the same declaration as M and has a type that is assignable to that of M.
o M is an optional property and S’ contains no property of the same name as M.
o M is a non-specialized call or construct signature and S’ contains a call or construct signature N where, when substituting ‘Object’ for all type parameters declared by M and N (if any),
§ the signatures are of the same kind (call or construct),
§ the number of non-optional parameters in N is less than or equal to that of M,
§ for parameter positions that are present in both signatures, each parameter type in N is assignable to or from the corresponding parameter type in M,
§ the result type of M is Void, or the result type of N is assignable to that of M.
o M is a numeric index signature of type U and S’ contains a string or numeric index signature of a type that is assignable to U.
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
Note that specialized call and construct signatures (section <IP_ADDRESS>) are not significant when determining assignment compatibility.
The assignment compatibility and subtyping rules differ only in that
Š the Any type is assignable to, but not a subtype of, all types, and
Š the primitive type Number is assignable to, but not a subtype of, all enum types.
The assignment compatibility rules imply that, when assigning values or passing parameters, optional properties must either be present and of a compatible type, or not be present at all. For example:
function foo(x: { id: number; name?: string; }):
void;
foo({ id: 1234 });
// Ok
foo({ id: 1234, name: "hello" });
// Ok
foo({ id: 1234, name: false }); // Error, name of wrong type
foo({ name: "hello" });
// Error, id required but missing
In several situations TypeScript infers types from context, alleviating the need for the programmer to explicitly specify types that appear obvious. For example
var name = "Steve";
infers the type of name to be the String primitive type since that is the type of the value used to initialize it. When inferring the type of a variable, property or function result from an expression, the widened form of the source type is used as the inferred type of the target. The widened form of a type is the type in which all occurrences of the Null and Undefined types have been replaced with the type any.
The following example shows the results of widening types to produce inferred variable types.
var
a = null;
// var a:
any
var b =
undefined;
// var b:
any
var c = {
x: 0, y:
null }; // var c: { x: number,
y: any }
var d = [ null, undefined
]; // var d: any[]
In some cases a best common type needs to be inferred from a set of types. In particular, return types of functions with multiple return statements and element types of array literals are found this way.
For an empty set of types, the best common type is the Any type.
For a non-empty set of types { T1, T2, …, Tn }, the best common type is the one Tx in the set that is a supertype of every Tn. It is possible that no such type exists, in which case the best common type is an empty object type (the type {}).
This chapter describes the manner in which TypeScript provides type inference and type checking for JavaScript expressions. TypeScript’s type analysis occurs entirely at compile-time and adds no run-time overhead to expression evaluation.
TypeScript’s typing rules define a type for every expression construct. For example, the type of the literal 123 is the Number primitive type, and the type of the object literal { a: 10, b: "hello" } is { a: number; b: string; }. The sections in this chapter describe these rules in detail.
In addition to type inference and type checking, TypeScript adds the following expression constructs:
Š Optional parameter and return type annotations in function expressions.
Š Default parameter values and rest parameters in function expressions.
Š Arrow function expressions.
Š Super calls and member access.
Š Type assertions.
Unless otherwise noted in the sections that follow, TypeScript expressions and the JavaScript expressions generated from them are identical.
Expressions are classified as values or references. References are the subset of expressions that are permitted as the target of an assignment. Specifically, references are combinations of identifiers (section 4.3), parentheses (section 4.7), and property accesses (section 4.10). All other expression constructs described in this chapter are classified as values.
The type of this in an expression depends on the location in which the reference takes place:
Š In a constructor, member function, or member accessor, this is of the class instance type of the containing class.
Š In a static function or static accessor, this is of a type corresponding to the constructor function type of the containing class without any construct signatures.
Š In a function declaration or a standard function expression, this is of type Any.
Š In the global module, this is of type Any.
In all other contexts it is a compile-time error to reference this.
In the body of an arrow function expression, references to this are rewritten in the generated JavaScript code, as described in section 4.9.2.
When an expression is an Identifier, the expression refers to the most nested module, class, enum, function, variable, or parameter with that name whose scope (section 2.4) includes the location of the reference.
The type of the expression is the type associated with the referenced entity:
Š For a module, the object type associated with the module instance.
Š For a class, the constructor type associated with the constructor function object.
Š For an enum, the object type associated with the enum object.
Š For a function, the function type associated with the function object.
Š For a variable, the type of the variable.
Š For a parameter, the type of the parameter.
In all cases, the expression is classified as a reference.
Literals are typed as follows:
Š The type of the null literal is the Null primitive type.
Š The type of the literals true and false is the Boolean primitive type.
Š The type of numeric literals is the Number primitive type.
Š The type of string literals is the String primitive type.
Š The type of regular expression literals is the RegExp interface type.
Object literals are extended to support type annotations in get and set accessors.
PropertyAssignment:
( Modified )
PropertyName : AssignmentExpression
PropertyName
CallSignature { FunctionBody }
GetAccessor
SetAccessor
GetAccessor:
get PropertyName ( ) TypeAnnotationopt { FunctionBody }
SetAccessor:
set PropertyName ( Identifier TypeAnnotationopt ) { FunctionBody }
The type of an object literal is an object type with the set of properties specified by the property assignments in the object literal. A get and set accessor may specify the same property name, but otherwise it is an error to specify multiple property assignments for the same property.
An property assignment of the form
PropertyName CallSignature { FunctionBody }
is simply shorthand for
PropertyName : function CallSignature { FunctionBody }
Each property assignment in an object literal is processed as follows:
Š If the object literal is contextually typed and the contextual type contains a property with a matching name, the property assignment is contextually typed by the type of that property.
Š Otherwise, if the object literal is contextually typed, the contextual type contains a numeric index signature, and the property assignment specifies a numeric property name, the property assignment is contextually typed by the type of the numeric index signature.
Š Otherwise, if the object literal is contextually typed and the contextual type contains a string index signature, the property assignment is contextually typed by the type of the string index signature.
Š Otherwise, the property assignment is processed without a contextual type.
The type of a property introduced by a property assignment of the form Name : Expr is the widened form (section 3.9) of the type of Expr.
A get accessor declaration is processed in the same manner as an ordinary function declaration (section 6.1) with no parameters. A set accessor declaration is processed in the same manner as an ordinary function declaration with a single parameter and a Void return type. When both a get and set accessor is declared for a property:
Š If both accessors include type annotations, the specified types must be identical.
Š If only one accessor includes a type annotation, the other behaves as if it had the same type annotation.
Š If neither accessor includes a type annotation, the inferred return type of the get accessor becomes the parameter type of the set accessor.
If a get accessor is declared for a property, the return type of the get accessor becomes the type of the property. If only a set accessor is declared for a property, the parameter type (which may be type Any if no type annotation is present) of the set accessor becomes the type of the property.
When an object literal is contextually typed by a type that includes a string index signature of type T, the resulting type of the object literal includes a string index signature with the best common type of T and the types of the properties declared in the object literal. Likewise, when an object literal is contextually typed by a type that includes a numeric index signature of type T, the resulting type of the object literal includes a numeric index signature with the best common type of T and the types of the numerically named properties (section 3.7.4) declared in the object literal.
In the absence of a contextual type, the type of an array literal is C[], where C is the best common type of the element expressions. Note that the type of an empty array literal is any[] since the Any type is the best common type of an empty set of types.
When an array literal is contextually typed (section 4.18) by an object type containing a numeric index signature of type T, each element expression is contextually typed by T and the type of the array literal is the best common type of T and the types of the element expressions.
A parenthesized expression
( Expression )
has the same type and classification as the Expression itself. Specifically, if the contained expression is classified as a reference, so is the parenthesized expression.
The super keyword can be used in expressions to reference base class properties and the base class constructor.
CallExpression: (
Modified )
…
super ( ArgumentListopt )
super . IdentifierName
Super calls consist of the keyword super followed by an argument list enclosed in parentheses. Super calls are only permitted in constructors of derived classes, as described in section 8.3.2.
A super call invokes the constructor of the base class on the instance referenced by this. A super call is processed as a function call (section 4.12) using the construct signatures of the base class constructor function type as the initial set of candidate signatures for overload resolution. Type arguments cannot be explicitly specified in a super call. If the base class is a generic class, the type arguments used to process a super call are always those specified in the extends clause that references the base class.
The type of a super call expression is Void.
The JavaScript code generated for a super call is specified in section 8.5.2.
A super property access consists of the keyword super followed by a dot and an identifier. Super property accesses are used to access base class member functions from derived classes.
Super property accesses are permitted as follows:
Š In a constructor, instance member function, or instance member accessor of a derived class, a super property access must specify a public instance member function of the base class.
Š In a static member function or static member accessor of a derived class, a super property access must specify a public static member function of the base class.
Super property accesses are not permitted in other contexts, and it is not possible to access other kinds of base class members in a super property access.
Super property accesses are typically used to access overridden base class member functions from derived class member functions. For an example of this, see section 8.4.2.
The JavaScript code generated for a super property access is specified in section 8.5.2.
Function expressions are extended from JavaScript to optionally include parameter and return type annotations, and a new compact form, called arrow function expressions, is introduced.
FunctionExpression:
( Modified )
function Identifieropt CallSignature { FunctionBody }
AssignmentExpression:
( Modified )
…
ArrowFunctionExpression
ArrowFunctionExpression:
ArrowFormalParameters => Block
ArrowFormalParameters => AssignmentExpression
ArrowFormalParameters:
CallSignature
Identifier
The terms standard function expression and arrow function expression are used to refer to the FunctionExpression and ArrowFunctionExpression forms respectively. When referring to either, the generic term function expression is used.
The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression’s signature and body.
The descriptions of function declarations provided in section 6.1 apply to function expressions as well, except that function expressions do not support overloading.
Standard function expressions are function expressions written with the function keyword. The type of this in a standard function expression is the Any type.
Standard function expressions are transformed to JavaScript in the same manner as function declarations (see section 6.5).
TypeScript supports arrow function expressions, a new feature planned for ECMAScript 6. Arrow function expressions are a compact form of function expressions that omit the function keyword and have lexical scoping of this.
An arrow function expression of the form
ArrowFormalParameters => AssignmentExpression
is exactly equivalent to
ArrowFormalParameters => { return AssignmentExpression ; }
Furthermore, arrow function expressions of the forms
Identifier => Block
Identifier => AssignmentExpression
are exactly equivalent to
( Identifier ) => Block
( Identifier ) => AssignmentExpression
Thus, the following examples are all equivalent:
(x) => { return Math.sin(x); }
(x) => Math.sin(x)
x => { return
Math.sin(x); }
x => Math.sin(x)
A function expression using the function keyword introduces a new dynamically bound this, whereas an arrow function expression preserves the this of its enclosing context. Arrow function expressions are particularly useful for writing callbacks, which otherwise would have a meaningless this.
In the example
var messenger = {
message: "Hello World",
start: function() {
setTimeout(() => { alert(this.message);
}, 3000);
}
};
messenger.start();
the use
of an arrow function expression causes the callback to have the same this as the surrounding start
function. Writing the callback as a standard function expression it becomes
necessary to manually arrange access to the surrounding this, for example by copying it into a
local variable:
var messenger = {
message: "Hello World",
start: function() {
var _this = this;
setTimeout(function() { alert(_this.message);
}, 3000);
}
};
messenger.start();
The TypeScript compiler applies this type of transformation to rewrite arrow function expressions into standard function expressions.
A construct of the form
< Identifier > ( ParamList ) => { ... }
could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former, but parentheses can be used to select the latter meaning:
< Identifier > ( ( ParamList ) => { ... } )
Function expressions with no type parameters and no parameter or return type annotations (but possibly with optional parameters and default parameter values) are contextually typed in certain circumstances, as described in section 4.18. When a function expression is contextually typed by a function type T, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in T. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than T, the additional parameters in T are ignored. If the function expression has more parameters than T, the additional parameters are all considered to have type Any.
When a function expression is contextually typed by a generic function type, parameters may be given types that are not directly denotable. In the example
interface
Comparable<T> {
compareTo(other: T): number;
}
interface
Comparer {
<T extends
Comparable<T>>(x: T, y: T): number;
}
var
f: Comparer = (x, y) => {
var z: any; // No name for type of x and y
...
}
the ‘Comparer’ type represents a function that can compare two values of some type ‘T’, where ‘T’ must implement ‘Comparable<T>’. In the function expression assigned to ‘f’, contextual typing provides a type for ‘x’ and ‘y’ that is identical in structure to the type parameter in ‘Comparer’ (i.e. ‘x’ and ‘y’ will have a ‘compareTo’ method taking an argument of the same type as themselves), but no name is introduced for the type. In order to introduce a name for the type the function expression must be explicitly typed:
var
f: Comparer = <T extends Comparable<T>>(x: T, y: T) => {
var z: T; // Z has same type as x and y
...
}
A property access uses either dot notation or bracket notation. A property access expression is always classified as a reference.
A property access applied to a value of the primitive type Number, Boolean, or String behaves exactly as a property access applied to an object of the global interface type ‘Number’, ‘Boolean’, or ‘String’ respectively. Likewise, a property access applied to a value of an enum type behaves exactly as a property access applied to an object of the global interface type ‘Number’.
In a property access, an object (including Number, Boolean, or String) appears to have additional properties that originate in the ‘Object’ or ‘Function’ global interface types, as described in section 3.3, and a type parameter appears to have the properties of its declared constraint, as described in section 3.4.
A dot notation property access of the form
ObjExpr . Name
where ObjExpr is an expression and Name is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time:
Š If ObjExpr is of type Any, any Name is permitted and the property access is of type Any.
Š Otherwise, if Name denotes a property member in the type of ObjExpr, the property access is of the type of that property.
Š Otherwise, the property access is invalid and a compile-time error occurs.
A bracket notation property access of the form
ObjExpr [ IndexExpr ]
where ObjExpr and IndexExpr are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time:
Š If IndexExpr is a string literal or a numeric literal and ObjExpr is of a type that has a property with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property.
Š Otherwise, if ObjExpr is of a type that has a numeric index signature and IndexExpr is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature.
Š Otherwise, if ObjExpr is of a type that has a string index signature and IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature.
Š Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.
Š Otherwise, the property access is invalid and a compile-time error occurs.
A new operation has one of the following forms:
new ConstructExpr
new ConstructExpr ( Args )
where ConstructExpr is an expression and Args is an argument list. The first form is equivalent to supplying an empty argument list. ConstructExpr must be of type Any or of an object type with one or more construct or call signatures. The operation is processed as follows at compile-time:
Š If ConstructExpr is of type Any, Args can be any argument list and the result of the operation is of type Any.
Š If ConstructExpr is of an object type with one or more construct signatures, the expression is processed in the same manner as a function call, but using the construct signatures as the initial set of candidate signatures for overload resolution. The result type of the function call becomes the result type of the operation.
Š If ConstructExpr is of an object type with no construct signatures but one or more call signatures, the expression is processed as a function call. A compile-time error occurs if the result of the function call is not Void. The type of the result of the operation is Any.
Function calls are extended from JavaScript to optionally include type arguments.
Arguments: (
Modified )
TypeArgumentsopt ( ArgumentListopt )
A function call takes one of the forms
FuncExpr ( Args )
FuncExpr < TypeArgs > ( Args )
where FuncExpr is an expression of a function type or of type Any, TypeArgs is a type argument list, and Args is an argument list.
If FuncExpr is of type Any, or of an object type that has no call signatures but is a subtype of the Function interface, the call is an untyped function call. In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual types are provided for the argument expressions, and the result is always of type Any.
If FuncExpr is of a function type, the call is a typed function call. TypeScript employs overload resolution in typed function calls in order to support functions with multiple call signatures. Furthermore, TypeScript may perform type argument inference to automatically determine type arguments in generic function calls.
The purpose of overload resolution in a function call is to ensure that at least one signature is applicable, to provide contextual types for the arguments, and to determine the result type of the function call, which could differ between the multiple applicable signatures. Overload resolution has no impact on the run-time behavior of a function call. Since JavaScript doesn’t support function overloading, all that matters at run-time is the name of the function.
The compile-time processing of a typed function call consists of the following steps:
Š First, a set of candidate signatures is constructed from the signatures in the function type.
o A non-generic signature is a candidate when
§ the function call has no type arguments, and
§ the signature is applicable with respect to the argument list of the function call.
o A generic signature is a candidate in a function call without type arguments when
§ type inference (section 4.12.2) succeeds in inferring a list of type arguments,
§ the inferred type arguments satisfy their constraints, and
§ once the inferred type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call.
o A generic signature is a candidate in a function call with type arguments when
§ The signature has the same number of type parameters as were supplied in the type argument list,
§ the type arguments satisfy their constraints, and
§ once the type arguments are substituted for their associated type parameters, the signature is applicable with respect to the argument list of the function call.
Š If the set of candidate signatures is empty, the function call is an error.
Š Otherwise, for every signature S in the set, if another signature is a better match for the argument list, S is eliminated from the set.
Š The result type of the call is the return type of the first remaining signature in the set in declaration order. For classes and interfaces, inherited signatures are considered to follow explicitly declared signatures in extends clause order.
A signature is said to be an applicable signature with respect to an argument list when
Š each non-optional parameter has a corresponding argument, and
Š each argument expression, contextually typed (section 4.18) by the corresponding parameter type in the signature, is of a type that is assignable to (section 3.8.3) that parameter type.
Given an argument list with a set of argument expressions { e1, e2, …, en } and two applicable signatures P and Q with parameter types { P1, P2, …, Pn } and { Q1, Q2, …, Qn }, P is a better match than Q when
Š for no argument, eX better matches QX than PX, and
Š for at least one argument, eX better matches PX than QX.
Given an expression e and two types T1 and T2, the better matching type is determined as follows:
Š If T1 and T2 are identical types, neither is a better match.
Š If e is a string literal and T1 is the corresponding string literal type, T1 is the better match.
Š If e is a string literal and T2 is the corresponding string literal type, T2 is the better match.
Š If the type of e is identical to T1, T1 is the better conversion.
Š If the type of e is identical to T2, T2 is the better conversion.
Š If T1 is a subtype of T2, T1 is the better match.
Š If T2 is a subtype of T1, T2 is the better match.
Š Otherwise, neither type is a better match.
Given a signature < T1 , T2 , … , Tn > ( p1 : P1 , p2 : P2 , … , pm : Pm ), where each parameter type P references zero or more of the type parameters T, and an argument list ( e1 , e2 , … , em ), the task of type argument inference is to find a set of type arguments A1…An to substitute for T1…Tn such that the argument list becomes an applicable signature.
The inferred type argument for a particular type parameter is the best common type (section 3.10) of a set of candidate types. In order to compute candidate types, the argument list is processed as follows:
Š Initially all inferred type arguments are considered unfixed with an empty set of candidate types.
Š Proceeding from left to right, each argument expression e is inferentially typed by its corresponding parameter type P, possibly causing some inferred type arguments to become fixed, and candidate type inferences are made for unfixed inferred type arguments by relating the type computed for e to P.
The process of inferentially typing an expression e by a type T is the same as that of contextually typing e by T, with the following exceptions:
Š Where expressions contained within e would be contextually typed, they are instead inferentially typed.
Š Where a contextual type would be included in a candidate set for a best common type (such as when inferentially typing an object or array literal), an inferential type is not.
Š When a function expression is inferentially typed (section 4.9.3) and a type assigned to a parameter in that function expression references type parameters for which inferences are being made, the corresponding inferred type arguments to become fixed and no further candidate inferences are made for them.
Candidate inferences are made by relating a type S to a type T as follows:
Š If S is not assignable to T when type Any is substituted for all type parameters, no candidate inferences are made.
Š Otherwise, if T is a type parameter with an unfixed inferred type argument, S is added to the set of candidate types for that type argument.
Š Otherwise, if S and T are object types, then for each member M in T:
o If M is a property and S contains a property N with the same name as M, inferences are made by relating the type of N to the type of M.
o If M is a call or construct signature, then for each signature N in S that is assignable to M when type Any is substituted for all type parameters, candidate inferences are made by relating parameter types in N to parameter types in the same position in M, and by relating the return type of N to the return type of M.
o If M is a string index signature, then for each string index signature N in S, inferences are made by relating the type of N to the type of M.
o If M is a numeric index signature, then for each string or numeric index signature N in S, inferences are made by relating the type of N to the type of M.
TODO: Examples. Include
example that demonstrates the inferred type is Any when the set of candidate
inferences is empty.
The inclusion of type arguments in the Arguments production (section 4.12) gives rise to certain ambiguities in the grammar for expressions. For example, the statement
f(g<A, B>(7));
could be interpreted as a call to ‘f’ with two arguments, ‘g < A’ and ‘B > (7)’. Alternatively, it could be interpreted as a call to ‘f’ with one argument, which is a call to a generic function ‘g’ with two type arguments and one regular argument.
The grammar ambiguity is resolved as follows: In a context where one possible interpretation of a sequence of tokens is an Arguments production, if the initial sequence of tokens forms a syntactically correct TypeArguments production and is followed by a ‘(‘ token, then the sequence of tokens is processed an Arguments production, and any other possible interpretation is discarded. Otherwise, the sequence of tokens is not considered an Arguments production.
This rule means that the call to ‘f’ above is interpreted as a call with one argument, which is a call to a generic function ‘g’ with two type arguments and one regular argument. However, the statements
f(g < A, B > 7);
f(g < A, B > +(7));
are both interpreted as calls to ‘f’ with two arguments.
TypeScript extends the JavaScript expression grammar with the ability to assert a type for an expression:
UnaryExpression: (
Modified )
…
< Type > UnaryExpression
A type assertion expression consists of a type enclosed in < and > followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are not checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing < and > are simply removed from the generated code.
A type assertion expression of the form < T > e requires the type of e to be assignable to T or T to be assignable to the type of e, or otherwise a compile-time error occurs. The type of the result is T.
Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that might be correct, but aren’t known to be correct. In the example
class Shape { ... }
class Circle extends
Shape { ... }
function createShape(kind: string): Shape {
if (kind === "circle")
return new
Circle();
...
}
var circle = <Circle>
createShape("circle");
the type annotations indicate that the ‘createShape’ function might return a ‘Circle’ (because ‘Circle’ is a subtype of ‘Shape’), but isn’t known to do so (because its return type is ‘Shape’). Therefore, a type assertion is needed to treat the result as a ‘Circle’.
As mentioned above, type assertions are not checked at run-time and it is up to the programmer to guard against errors, for example using the instanceof operator:
var shape = createShape(shapeKind);
if (shape instanceof
Circle) {
var circle = <Circle> shape;
...
}
The subsections that follow specify the compile-time processing rules of the unary operators. In general, if the operand of a unary operator does not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type Any in further processing.
These operators, in prefix or postfix form, require their operand to be of type Any, the Number primitive type, or an enum type, and classified as a reference (section 4.1). They produce a result of the Number primitive type.
These operators permit their operand to be of any type and produce a result of the Number primitive type.
The unary + operator can conveniently be used to convert a value of any type to the Number primitive type:
function getValue() { ... }
var n = +getValue();
The example above converts the result of ‘getValue()’ to a number if it isn’t a number already. The type inferred for ‘n’ is the Number primitive type regardless of the return type of ‘getValue’.
The ! operator permits its operand to be of any type and produces a result of the Boolean primitive type.
Two unary ! operators in sequence can conveniently be used to convert a value of any type to the Boolean primitive type:
function getValue() { ... }
var b = !!getValue();
The example above converts the result of ‘getValue()’ to a Boolean if it isn’t a Boolean already. The type inferred for ‘b’ is the Boolean primitive type regardless of the return type of ‘getValue’.
The delete operator takes an operand of any type and produces a result of the Boolean primitive type.
The void operator takes an operand of any type and produces the value undefined. The type of the result is the Undefined type (3.2.6).
The typeof operator takes an operand of any type and produces a value of the String primitive type.
The subsections that follow specify the compile-time processing rules of the binary operators. In general, if the operands of a binary operator do not meet the stated requirements, a compile-time error occurs and the result of the operation defaults to type any in further processing. Tables that summarize the compile-time processing rules for operands of the Any type, the Boolean, Number, and String primitive types, and all object types and type parameters (the Object column in the tables) are provided.
These operators require their operands to be of type Any, the Number primitive type, or an enum type. Operands of an enum type are treated as having the primitive type Number. If one operand is the null or undefined value, it is treated as having the type of the other operand. The result is always of the Number primitive type.
|
|
Any |
Boolean |
Number |
String |
Object |
|
Any |
Number |
|
Number |
|
|
|
Boolean |
|
|
|
|
|
|
Number |
Number |
|
Number |
|
|
|
String |
|
|
|
|
|
|
Object |
|
|
|
|
|
The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive type. Operands of an enum type are treated as having the primitive type Number. If one operand is the null or undefined value, it is treated as having the type of the other operand. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any.
|
|
Any |
Boolean |
Number |
String |
Object |
|
Any |
Any |
Any |
Any |
String |
Any |
|
Boolean |
Any |
|
|
String |
|
|
Number |
Any |
|
Number |
String |
|
|
String |
String |
String |
String |
String |
String |
|
Object |
Any |
|
|
String |
|
A value of any type can converted to the String primitive type by adding an empty string:
function getValue() { ... }
var s = getValue() + "";
The example above converts the result of ‘getValue()’ to a string if it isn’t a string already. The type inferred for ‘s’ is the String primitive type regardless of the return type of ‘getValue’.
These operators require one operand type to be identical to or a subtype of the other operand type. The result is always of the Boolean primitive type.
|
|
Any |
Boolean |
Number |
String |
Object |
|
Any |
Boolean |
Boolean |
Boolean |
Boolean |
Boolean |
|
Boolean |
Boolean |
Boolean |
|
|
|
|
Number |
Boolean |
|
Boolean |
|
|
|
String |
Boolean |
|
|
Boolean |
|
|
Object |
Boolean |
|
|
|
Boolean |
The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the ‘Function’ interface type. The result is always of the Boolean primitive type.
Note that object types containing one or more call or construct signatures are automatically subtypes of the ‘Function’ interface type, as described in section 3.3.
The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any, an object type, or a type parameter type. The result is always of the Boolean primitive type.
The && operator permits the operands to be of any type and produces a result of the same type as the second operand.
|
|
Any |
Boolean |
Number |
String |
Object |
|
Any |
Any |
Boolean |
Number |
String |
Object |
|
Boolean |
Any |
Boolean |
Number |
String |
Object |
|
Number |
Any |
Boolean |
Number |
String |
Object |
|
String |
Any |
Boolean |
Number |
String |
Object |
|
Object |
Any |
Boolean |
Number |
String |
Object |
The || operator permits the operands to be of any type and produces a result that is of the best common type (section 3.10) of the two operand types.
|
|
Any |
Boolean |
Number |
String |
Object |
|
Any |
Any |
Any |
Any |
Any |
Any |
|
Boolean |
Any |
Boolean |
{ } |
{ } |
{ } |
|
Number |
Any |
{ } |
Number |
{ } |
{ } |
|
String |
Any |
{ } |
{ } |
String |
{ } |
|
Object |
Any |
{ } |
{ } |
{ } |
Object |
In a conditional expression of the form
Cond ? Expr1 : Expr2
the Cond expression may be of any type, and Expr1 and Expr2 expressions must be of identical types or the type of one must be a subtype of the other. The result is of the best common type (section 3.10) of the two expression types.
An assignment of the form
VarExpr = ValueExpr
requires VarExpr to be classified as a reference (section 4.1). ValueExpr is contextually typed (section 4.18) by the type of VarExpr, and the type of ValueExpr must be assignable to (section 3.8.3) the type of VarExpr, or otherwise a compile-time error occurs. The result is a value with the type of ValueExpr.
A compound assignment of the form
VarExpr Operator= ValueExpr
where Operator= is of the compound assignment operators
*= /= %= += -= <<= >>= >>>= &= ^= |=
is subject to the same requirements, and produces a value of the same type, as the corresponding non-compound operation. A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) and the type of the non-compound operation to be assignable to the type of VarExpr.
In certain situations, parameter and return types of function expressions are automatically inferred from the contexts in which the function expressions occur. For example, given the declaration
var f: (s: string) => string;
the assignment
f = function(s) { return s.toLowerCase(); }
infers the type of the ‘s’ parameter to be the String primitive type even though there is no type annotation to that effect. The function expression is said to be contextually typed by the variable to which it is being assigned. Contextual typing occurs in the following situations:
Š In variable and member declarations with a type annotation and an initializer, the initializer expression is contextually typed by the type of the variable or property.
Š In assignment expressions, the right hand expression is contextually typed by the type of the left hand expression.
Š In typed function calls, argument expressions are contextually typed by their parameter types.
Š In return statements, if the containing function has a known return type, the expression is contextually typed by that return type. A function’s return type is known if the function includes a return type annotation or is itself contextually typed.
Š In contextually typed object literals, property assignments are contextually typed by their property types.
Š In contextually typed array literals, element expressions are contextually typed by the array element type.
Contextual typing of an expression e by a type T proceeds as follows:
Š If e is an ObjectLiteral and T is an object type, e is processed with the contextual type T, as described in section 4.5.
Š If e is an ArrayLiteral and T is an object type with a numeric index signature, e is processed with the contextual type T, as described in section 4.6.
Š If e is a FunctionExpression or ArrowFunctionExpression with no type parameters and no parameter or return type annotations, and T is an object type with exactly one call signature, e is processed with the contextual type T, as described in section 4.9.3.
Š Otherwise, e is processed without a contextual type.
The rules above require expressions be of the exact syntactic forms specified in order to be processed as contextually typed constructs. 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.
In the following example
interface EventObject {
x: number;
y: number;
}
interface EventHandlers {
mousedown?: (event:
EventObject) => void;
mouseup?: (event:
EventObject) => void;
mousemove?: (event:
EventObject) => void;
}
function setEventHandlers(handlers:
EventHandlers) { ... }
setEventHandlers({
mousedown: e => {
startTracking(e.x, e.y); },
mouseup: e => {
endTracking(); }
});
the object literal passed to ‘setEventHandlers’ is contextually typed to the ‘EventHandlers’ type. This causes the two property assignments to be contextually typed to the unnamed function type ‘(event: EventObject) => void’, which in turn causes the ‘e’ parameters in the arrow function expressions to automatically be typed as ‘EventObject’.
TODO: Describe type
checking for 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 };
TypeScript extends JavaScript functions to include type parameters, parameter and return type annotations, overloads, default parameter values, and rest parameters.
Function declarations consist of an optional set of function overloads followed by an actual function implementation.
FunctionDeclaration:
( Modified )
FunctionOverloadsopt
FunctionImplementation
FunctionOverloads:
FunctionOverload
FunctionOverloads FunctionOverload
FunctionOverload:
function Identifier CallSignature ;
FunctionImplementation:
function Identifier CallSignature { FunctionBody }
A function declaration introduces a function with the given name in the containing declaration space. Function overloads, if present, must specify the same name as the function implementation. If a function declaration includes overloads, the overloads determine the call signatures of the type given to the function object and the function implementation signature must be assignable to that type. Otherwise, the function implementation itself determines the call signature. Function overloads have no other effect on a function declaration.
Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function’s return type varies based on its arguments. Overload resolution in function calls is described further in section 4.12.
Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost.
The parameter list of a function overload cannot specify default values for parameters. In other words, an overload may use only the ? form when specifying optional parameters.
It is an error to declare multiple function overloads that are considered identical (section 3.8.1) or differ only in their return types.
The following is an example of a function with overloads.
function
attr(name: string):
string;
function
attr(name: string,
value: string):
Accessor;
function
attr(map: any):
Accessor;
function
attr(nameOrMap: any,
value?: string):
any {
if (nameOrMap
&& typeof
nameOrMap === "object")
{
// handle
map case
}
else {
// handle
string case
}
}
Note that each overload and the final implementation specify the same identifier. The type of the local variable ‘attr’ introduced by this declaration is
var
attr: {
(name: string): string;
(name: string, value: string):
Accessor;
(map: any): Accessor;
};
Note that the signature of the actual function implementation is not included in the type.
A function implementation without a return type annotation is said to be an implicitly typed function. The return type of an implicitly typed function f is inferred from its function body as follows:
Š If there are no return statements with expressions in f’s function body, the inferred return type is Void.
Š Otherwise, if f’s function body directly references f or references any implicitly typed functions that through this same analysis reference f, the inferred return type is Any.
Š Otherwise, the inferred return type is the widened form (section 3.9) of the best common type (section 3.10) of the types of the return statement expression in the function body, ignoring return statements with no expressions. A compile-time error occurs if the best common type isn’t one of the return statement expression types (i.e. if the best common type is an empty type).
In the example
function
f(x: number)
{
if (x <= 0) return x;
return g(x);
}
function
g(x: number)
{
return f(x
– 1);
}
the inferred return type for ‘f’ and ‘g’ is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type ‘number’ to either breaks the cycle and causes the return type ‘number’ to be inferred for the other.
The type of this in a function implementation is the Any type.
In the signature of a function implementation, a parameter can be marked optional by following it with an initializer. An optional parameter with an initializer but no type annotation has its type inferred from the initializer. Specifically, the type of such a parameter is the widened form of the type of the initializer expression. An initializer expression for a given parameter is permitted to reference parameters that are declared to the left of that parameter, but it is a compile-time error to access other parameters or locals. For each parameter with an initializer, a statement that substitutes the default value for an omitted argument is included in the generated JavaScript, as described in section 6.3. The example
function
strange(x: number,
y = x * 2,
z = x + y) {
return z;
}
generates JavaScript that is equivalent to
function
strange(x, y, z) {
if (typeof y === "undefined")
{ y = x * 2;
}
if (typeof z === "undefined")
{ z = x + y; }
return z;
}
A function implementation may include type parameters in its signature (section <IP_ADDRESS>) and is then called a generic function. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct.
Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation.
The following is an example of a generic function:
interface
Comparable<T> {
localeCompare(other:
T): number;
}
function
compare<T extends
Comparable<T>>(x: T, y: T): number {
if (x == null) return y == null
? 0 : -1;
if (y == null) return 1;
return x.localeCompare(y);
}
Note that the ‘x’ and ‘y’ parameters are known to be subtypes of the constraint ‘Comparable<T>’ and therefore have a ‘compareTo’ member. This is described further in section 3.4.
The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section 4.12.2) from the types of the regular arguments in the call. In the example
class
Person {
name: string;
localeCompare(other:
Person) {
return
compare(this.name, other.name);
}
}
the type argument to ‘compare’ is automatically inferred to be the String type because the two arguments are strings.
A function declaration generates JavaScript code that is equivalent to:
function
<FunctionName>(<FunctionParameters>) {
<DefaultValueAssignments>
<FunctionStatements>
}
FunctionName is the name of the function (or nothing in the case of a function expression).
FunctionParameters is a comma separated list of the function’s parameter names.
DefaultValueAssignments is a sequence of default property value assignments, one for each parameter with a default value, in the order they are declared, of the form
if (typeof <Parameter> === "undefined") { <Parameter> = <Default>; }
where Parameter is the parameter name and Default is the default value expression.
FunctionStatements is the code generated for the statements specified in the function body.
Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones.
 Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions.
Because TypeScript has a structural type system, an interface type with a particular set of members is considered identical to, and can be substituted for, another interface type or object type literal with an identical set of members (see section 3.8.1).
Class declarations may reference interfaces in their implements clause to validate that they provide an implementation of the interfaces.
An interface declaration declares a new named type (section 3.5) by introducing a type name in the containing module.
InterfaceDeclaration:
interface Identifier TypeParametersopt InterfaceExtendsClauseopt ObjectType
InterfaceExtendsClause:
extends ClassOrInterfaceTypeList