mirror of
https://github.com/microsoft/TypeScript.git
synced 2026-06-14 16:56:06 -05:00
Decomposed TypeScript specification into independent Markdown files per section.
This commit is contained in:
146
doc/spec/Ambients.md
Normal file
146
doc/spec/Ambients.md
Normal file
@@ -0,0 +1,146 @@
|
||||
# Ambients { #ambients }
|
||||
|
||||
Ambient declarations are used to provide static typing over existing JavaScript code. Ambient declarations differ from regular declarations in that no JavaScript code is emitted for them. Instead of introducing new variables, functions, classes, enums, or namespaces, ambient declarations provide type information for entities that exist "ambiently" and are included in a program by external means, for example by referencing a JavaScript library in a <script/> tag.
|
||||
|
||||
## Ambient Declarations { #ambients-ambient-declarations }
|
||||
|
||||
Ambient declarations are written using the `declare` keyword and can declare variables, functions, classes, enums, namespaces, or modules.
|
||||
|
||||
  *AmbientDeclaration:*
|
||||
   `declare` *AmbientVariableDeclaration*
|
||||
   `declare` *AmbientFunctionDeclaration*
|
||||
   `declare` *AmbientClassDeclaration*
|
||||
   `declare` *AmbientEnumDeclaration*
|
||||
   `declare` *AmbientNamespaceDeclaration*
|
||||
|
||||
### Ambient Variable Declarations { #ambient-variable-declarations }
|
||||
|
||||
An ambient variable declaration introduces a variable in the containing declaration space.
|
||||
|
||||
  *AmbientVariableDeclaration:*
|
||||
   `var` *AmbientBindingList* `;`
|
||||
   `let` *AmbientBindingList* `;`
|
||||
   `const` *AmbientBindingList* `;`
|
||||
|
||||
  *AmbientBindingList:*
|
||||
   *AmbientBinding*
|
||||
   *AmbientBindingList* `,` *AmbientBinding*
|
||||
|
||||
  *AmbientBinding:*
|
||||
   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>*
|
||||
|
||||
An ambient variable declaration may optionally include a type annotation. If no type annotation is present, the variable is assumed to have type Any.
|
||||
|
||||
An ambient variable declaration does not permit an initializer expression to be present.
|
||||
|
||||
### Ambient Function Declarations { #ambient-function-declarations }
|
||||
|
||||
An ambient function declaration introduces a function in the containing declaration space.
|
||||
|
||||
  *AmbientFunctionDeclaration:*
|
||||
   `function` *BindingIdentifier* *CallSignature* `;`
|
||||
|
||||
Ambient functions may be overloaded by specifying multiple ambient function declarations with the same name, but it is an error to declare multiple overloads that are considered identical (section [#type-and-member-identity]<!--3.11.2-->) or differ only in their return types.
|
||||
|
||||
Ambient function declarations cannot specify a function bodies and do not permit default parameter values.
|
||||
|
||||
### Ambient Class Declarations { #ambient-class-declarations }
|
||||
|
||||
An ambient class declaration declares a class type and a constructor function in the containing declaration space.
|
||||
|
||||
  *AmbientClassDeclaration:*
|
||||
   `class` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *AmbientClassBody* `}`
|
||||
|
||||
  *AmbientClassBody:*
|
||||
   *AmbientClassBodyElements<sub>opt</sub>*
|
||||
|
||||
  *AmbientClassBodyElements:*
|
||||
   *AmbientClassBodyElement*
|
||||
   *AmbientClassBodyElements* *AmbientClassBodyElement*
|
||||
|
||||
  *AmbientClassBodyElement:*
|
||||
   *AmbientConstructorDeclaration*
|
||||
   *AmbientPropertyMemberDeclaration*
|
||||
   *IndexSignature*
|
||||
|
||||
  *AmbientConstructorDeclaration:*
|
||||
   `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;`
|
||||
|
||||
  *AmbientPropertyMemberDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* `;`
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;`
|
||||
|
||||
### Ambient Enum Declarations { #ambient-enum-declarations }
|
||||
|
||||
An ambient enum is grammatically equivalent to a non-ambient enum declaration.
|
||||
|
||||
  *AmbientEnumDeclaration:*
|
||||
   *EnumDeclaration*
|
||||
|
||||
Ambient enum declarations differ from non-ambient enum declarations in two ways:
|
||||
|
||||
* In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions.
|
||||
* In ambient enum declarations that specify no `const` modifier, enum member declarations that omit a value are considered computed members (as opposed to having auto-incremented values assigned).
|
||||
|
||||
Ambient enum declarations are otherwise processed in the same manner as non-ambient enum declarations.
|
||||
|
||||
### Ambient Namespace Declarations { #ambient-namespace-declarations }
|
||||
|
||||
An ambient namespace declaration declares a namespace.
|
||||
|
||||
  *AmbientNamespaceDeclaration:*
|
||||
   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}`
|
||||
|
||||
  *AmbientNamespaceBody:*
|
||||
   *AmbientNamespaceElements<sub>opt</sub>*
|
||||
|
||||
  *AmbientNamespaceElements:*
|
||||
   *AmbientNamespaceElement*
|
||||
   *AmbientNamespaceElements* *AmbientNamespaceElement*
|
||||
|
||||
  *AmbientNamespaceElement:*
|
||||
   `export`*<sub>opt</sub>* *AmbientVariableDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientLexicalDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientFunctionDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientClassDeclaration*
|
||||
   `export`*<sub>opt</sub>* *InterfaceDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientEnumDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientNamespaceDeclaration*
|
||||
   `export`*<sub>opt</sub>* *ImportAliasDeclaration*
|
||||
|
||||
Except for *ImportAliasDeclarations*, *AmbientNamespaceElements* always declare exported entities regardless of whether they include the optional `export` modifier.
|
||||
|
||||
## Ambient Module Declarations { #ambient-module-declarations }
|
||||
|
||||
An *AmbientModuleDeclaration* declares a module. This type of declaration is permitted only at the top level in a source file that contributes to the global namespace (section [#programs-and-source-files]<!--11.1-->). The *StringLiteral* must specify a top-level module name. Relative module names are not permitted.
|
||||
|
||||
  *AmbientModuleDeclaration:*
|
||||
   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}`
|
||||
|
||||
An *ImportRequireDeclaration* in an *AmbientModuleDeclaration* may reference other modules only through top-level module names. Relative module names are not permitted.
|
||||
|
||||
If an ambient module declaration includes an export assignment, it is an error for any of the declarations within the module to specify an `export` modifier. If an ambient module declaration contains no export assignment, entities declared in the module are exported regardless of whether their declarations include the optional `export` modifier.
|
||||
|
||||
Ambient modules are "open-ended" and ambient module declarations with the same string literal name contribute to a single module. For example, the following two declarations of a module 'io' might be located in separate source files.
|
||||
|
||||
```TypeScript
|
||||
declare module "io" {
|
||||
export function readFile(filename: string): string;
|
||||
}
|
||||
|
||||
declare module "io" {
|
||||
export function writeFile(filename: string, data: string): void;
|
||||
}
|
||||
```
|
||||
|
||||
This has the same effect as a single combined declaration:
|
||||
|
||||
```TypeScript
|
||||
declare module "io" {
|
||||
export function readFile(filename: string): string;
|
||||
export function writeFile(filename: string, data: string): void;
|
||||
}
|
||||
```
|
||||
|
||||
<br/>
|
||||
|
||||
244
doc/spec/Basic Concepts.md
Normal file
244
doc/spec/Basic Concepts.md
Normal file
@@ -0,0 +1,244 @@
|
||||
# Basic Concepts { #basic-concepts }
|
||||
|
||||
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 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th 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.
|
||||
|
||||
## Grammar Conventions { #grammar-conventions }
|
||||
|
||||
The syntactic grammar added by TypeScript language is specified throughout this document using the existing conventions and production names of the ECMAScript grammar. In places where TypeScript augments an existing grammar production it is so noted. For example:
|
||||
|
||||
  *Declaration:* *( Modified )*
|
||||
   …
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
|
||||
The '*( Modified )*' annotation indicates that an existing grammar production is being replaced, and the '…' references the contents of the original grammar production.
|
||||
|
||||
Similar to the ECMAScript grammar, if the phrase "*[no LineTerminator here]*" appears in the right-hand side of a production of the syntactic grammar, it indicates that the production is not a match if a *LineTerminator* occurs in the input stream at the indicated position.
|
||||
|
||||
## Names { #names }
|
||||
|
||||
A core purpose of the TypeScript compiler is to track the named entities in a program and validate that they are used according to their designated meaning. Names in TypeScript can be written in several ways, depending on context. Specifically, a name can be written as
|
||||
|
||||
* an *IdentifierName*,
|
||||
* a *StringLiteral* in a property name,
|
||||
* a *NumericLiteral* in a property name, or
|
||||
* a *ComputedPropertyName* that denotes a well-known symbol ([#computed-property-names]<!--2.2.3-->).
|
||||
|
||||
Most commonly, names are written to conform with the *Identifier* production, which is any *IdentifierName* that isn't a reserved word.
|
||||
|
||||
### Reserved Words { #reserved-words }
|
||||
|
||||
The following keywords are reserved and cannot be used as an *Identifier*:
|
||||
|
||||
```TypeScript
|
||||
break case catch class
|
||||
const continue debugger default
|
||||
delete do else enum
|
||||
export extends false finally
|
||||
for function if import
|
||||
in instanceof new null
|
||||
return super switch this
|
||||
throw true try typeof
|
||||
var void while with
|
||||
```
|
||||
|
||||
The following keywords cannot be used as identifiers in strict mode code, but are otherwise not restricted:
|
||||
|
||||
```TypeScript
|
||||
implements interface let package
|
||||
private protected public static
|
||||
yield
|
||||
```
|
||||
|
||||
The following keywords cannot be used as user defined type names, but are otherwise not restricted:
|
||||
|
||||
```TypeScript
|
||||
any boolean number string
|
||||
symbol
|
||||
```
|
||||
|
||||
The following keywords have special meaning in certain contexts, but are valid identifiers:
|
||||
|
||||
```TypeScript
|
||||
abstract as async await
|
||||
constructor declare from get
|
||||
is module namespace of
|
||||
require set type
|
||||
```
|
||||
|
||||
### Property Names { #property-names }
|
||||
|
||||
The *PropertyName* production from the ECMAScript grammar is reproduced below:
|
||||
|
||||
  *PropertyName:*
|
||||
   *LiteralPropertyName*
|
||||
   *ComputedPropertyName*
|
||||
|
||||
  *LiteralPropertyName:*
|
||||
   *IdentifierName*
|
||||
   *StringLiteral*
|
||||
   *NumericLiteral*
|
||||
|
||||
  *ComputedPropertyName:*
|
||||
   `[` *AssignmentExpression* `]`
|
||||
|
||||
A property name can be any identifier (including a reserved word), a string literal, a numeric literal, or a computed property name. String literals may 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.
|
||||
|
||||
### Computed Property Names { #computed-property-names }
|
||||
|
||||
ECMAScript 2015 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form
|
||||
|
||||
```TypeScript
|
||||
[ Symbol . xxx ]
|
||||
```
|
||||
|
||||
In a well-known symbol, the identifier to the right of the dot must denote a property of the primitive type `symbol` in the type of the global variable 'Symbol', or otherwise an error occurs.
|
||||
|
||||
In a *PropertyName* that specifies a *ComputedPropertyName*, the computed property name is required to denote a well-known symbol unless the property name occurs in a property assignment of an object literal ([#object-literals]<!--4.5-->) or a property member declaration in a non-ambient class ([#property-member-declarations]<!--8.4-->).
|
||||
|
||||
Below is an example of an interface that declares a property with a well-known symbol name:
|
||||
|
||||
```TypeScript
|
||||
interface Iterable<T> {
|
||||
[Symbol.iterator](): Iterator<T>;
|
||||
}
|
||||
```
|
||||
|
||||
*TODO: Update to reflect treatment of [computed property names with literal expressions](https://github.com/Microsoft/TypeScript/pull/5535)*.
|
||||
|
||||
## Declarations { #declarations }
|
||||
|
||||
Declarations introduce names in their associated ***declaration spaces***. A name must be unique in its declaration space and can denote a ***value***, a ***type***, or a ***namespace***, or some combination thereof. Effectively, a single name can have as many as three distinct meanings. For example:
|
||||
|
||||
```TypeScript
|
||||
var X: string; // Value named X
|
||||
|
||||
type X = number; // Type named X
|
||||
|
||||
namespace X { // Namespace named X
|
||||
type Y = string;
|
||||
}
|
||||
```
|
||||
|
||||
A name that denotes a value has an associated type (section [#types]<!--3-->) and can be referenced in expressions (section [#identifiers]<!--4.3-->). A name that denotes a type can be used by itself in a type reference or on the right hand side of a dot in a type reference ([#type-references]<!--3.8.2-->). A name that denotes a namespace can be used one the left hand side of a dot in a type reference.
|
||||
|
||||
When a name with multiple meanings is referenced, the context in which the reference occurs determines the meaning. For example:
|
||||
|
||||
```TypeScript
|
||||
var n: X; // X references type
|
||||
var s: X.Y = X; // First X references namespace, second X references value
|
||||
```
|
||||
|
||||
In the first line, X references the type X because it occurs in a type position. In the second line, the first X references the namespace X because it occurs before a dot in a type name, and the second X references the variable X because it occurs in an expression.
|
||||
|
||||
Declarations introduce the following meanings for the name they declare:
|
||||
|
||||
* A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning.
|
||||
* An interface, type alias, or type parameter declaration introduces a type meaning.
|
||||
* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class type).
|
||||
* An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type).
|
||||
* A namespace declaration introduces a namespace meaning (the type and namespace container) and, if the namespace is instantiated (section [#namespace-declarations]<!--10.1-->), a value meaning (the namespace instance).
|
||||
* An import or export declaration introduces the meaning(s) of the imported or exported entity.
|
||||
|
||||
Below are some examples of declarations that introduce multiple meanings for a name:
|
||||
|
||||
```TypeScript
|
||||
class C { // Value and type named C
|
||||
x: string;
|
||||
}
|
||||
|
||||
namespace N { // Value and namespace named N
|
||||
export var x: string;
|
||||
}
|
||||
```
|
||||
|
||||
Declaration spaces exist as follows:
|
||||
|
||||
* The global namespace, each module, and each declared namespace has a declaration space for its contained entities (whether local or exported).
|
||||
* Each module has a declaration space for its exported entities. All export declarations in the module contribute to this declaration space.
|
||||
* Each declared namespace has a declaration space for its exported entities. All export declarations in the namespace contribute to this declaration space. A declared namespace’s declaration space is shared with other declared namespaces that have the same root container and the same qualified name starting from that root container.
|
||||
* Each class declaration has a declaration space for instance members and type parameters, and a declaration space for static members.
|
||||
* Each interface declaration has a declaration space for members and type parameters. An interface's declaration space is shared with other interfaces that have the same root container and the same qualified name starting from that root container.
|
||||
* 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 container and the same qualified name starting from that root container.
|
||||
* Each type alias declaration has a declaration space for its type parameters.
|
||||
* Each function-like declaration (including function declarations, constructor declarations, member function declarations, member accessor declarations, function expressions, and arrow functions) has a declaration space for locals and type parameters. This declaration space includes parameter declarations, all local var and function declarations, and local let, const, class, interface, type alias, and enum declarations that occur immediately within the function body and are not further nested in blocks.
|
||||
* Each statement block has a declaration space for local let, const, class, interface, type alias, and enum declarations that occur immediately within that block.
|
||||
* 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 namespace***. Top-level declarations in a source file with one or more top-level import or export declarations belong to the ***module*** represented by that source file.
|
||||
|
||||
The ***container*** of an entity is defined as follows:
|
||||
|
||||
* The container of an entity declared in a namespace declaration is that namespace declaration.
|
||||
* The container of an entity declared in a module is that module.
|
||||
* The container of an entity declared in the global namespace is the global namespace.
|
||||
* The container of a module is the global namespace.
|
||||
|
||||
The ***root container*** of an entity is defined as follows:
|
||||
|
||||
* The root container of a non-exported entity is the entity’s container.
|
||||
* The root container of an exported entity is the root container of the entity's container.
|
||||
|
||||
Intuitively, the root container of an entity is the outermost module or namespace body from within which the entity is reachable.
|
||||
|
||||
Interfaces, enums, and namespaces are "open ended," meaning that interface, enum, and namespace declarations with the same qualified name relative to a common root are automatically merged. For further details, see sections [#declaration-merging]<!--7.2-->, [#declaration-merging]<!--9.3-->, and [#declaration-merging]<!--10.5-->.
|
||||
|
||||
Instance and static members in a class are in separate declaration spaces. Thus the following is permitted:
|
||||
|
||||
```TypeScript
|
||||
class C {
|
||||
x: number; // Instance member
|
||||
static x: string; // Static member
|
||||
}
|
||||
```
|
||||
|
||||
## Scopes { #scopes }
|
||||
|
||||
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 a name declared in the global namespace is the entire program text.
|
||||
* The scope of a name declared in a module is the source file of that module.
|
||||
* The scope of an exported name declared within a namespace declaration is the body of that namespace declaration and every namespace declaration with the same root and the same qualified name relative to that root.
|
||||
* The scope of a non-exported name declared within a namespace declaration is the body of that namespace declaration.
|
||||
* The scope of a type parameter name 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 name declared in a type alias declaration is that entire type alias declaration.
|
||||
* The scope of a member name declared in an enum declaration is the body of that declaration and every enum declaration with the same root and the same qualified name relative to that root.
|
||||
* The scope of a type parameter name 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 name declared in a call or construct signature is the remainder of the signature declaration. If the signature is part of a function-like declaration with a body (including a function declaration, constructor declaration, member function declaration, member accessor declaration, function expression, or arrow function), the scope includes the body of that function-like declaration.
|
||||
* The scope of a local var or function name declared anywhere in the body of a function-like declaration is the body of that function-like declaration.
|
||||
* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within the body of a function-like declaration is the body of that function-like declaration.
|
||||
* The scope of a local let, const, class, interface, type alias, or enum declaration declared immediately within a statement block is the body of that statement block.
|
||||
|
||||
Scopes may overlap, for example through nesting of namespaces and functions. When the scopes of two names overlap, the name with the innermost declaration takes precedence and access to the outer name is either not possible or only possible by qualification.
|
||||
|
||||
When an identifier is resolved as a *PrimaryExpression* (section [#identifiers]<!--4.3-->), only names in scope with a value meaning are considered and other names are ignored.
|
||||
|
||||
When an identifier is resolved as a *TypeName* (section [#type-references]<!--3.8.2-->), only names in scope with a type meaning are considered and other names are ignored.
|
||||
|
||||
When an identifier is resolved as a *NamespaceName* (section [#type-references]<!--3.8.2-->), only names in scope with a namespace meaning are considered and other names are ignored.
|
||||
|
||||
*TODO: [Include specific rules for alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*.
|
||||
|
||||
Note that class and interface members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class or interface instance. 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 a namespace are closer in scope than exported entities declared in other namespace declarations for the same namespace. For example:
|
||||
|
||||
```TypeScript
|
||||
var x = 1;
|
||||
namespace M {
|
||||
export var x = 2;
|
||||
console.log(x); // 2
|
||||
}
|
||||
namespace M {
|
||||
console.log(x); // 2
|
||||
}
|
||||
namespace M {
|
||||
var x = 3;
|
||||
console.log(x); // 3
|
||||
}
|
||||
```
|
||||
|
||||
<br/>
|
||||
|
||||
766
doc/spec/Classes.md
Normal file
766
doc/spec/Classes.md
Normal file
@@ -0,0 +1,766 @@
|
||||
# Classes { #classes }
|
||||
|
||||
TypeScript extends JavaScript classes to include type parameters, implements clauses, accessibility modifiers, member variable declarations, and parameter property declarations in constructors.
|
||||
|
||||
*TODO: Document [abstract classes](https://github.com/Microsoft/TypeScript/issues/3578)*.
|
||||
|
||||
## Class Declarations { #class-declarations }
|
||||
|
||||
A class declaration declares a ***class type*** and a ***constructor function***.
|
||||
|
||||
  *ClassDeclaration:* *( Modified )*
|
||||
   `class` *BindingIdentifier<sub>opt</sub>* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *ClassBody* `}`
|
||||
|
||||
A *ClassDeclaration* introduces a named type (the class type) and a named value (the constructor function) in the containing declaration space. The class type is formed from the instance members declared in the class body and the instance members inherited from the base class. The constructor function is given an anonymous type formed from the constructor declaration, the static member declarations in the class body, and the static members inherited from the base class. The constructor function initializes and returns an instance of the class type.
|
||||
|
||||
The *BindingIdentifier* of a class declaration may not be one of the predefined type names (section [#predefined-types]<!--3.8.1-->). The *BindingIdentifier* is optional only when the class declaration occurs in an export default declaration (section [#export-default-declarations]<!--11.3.4.2-->).
|
||||
|
||||
A class may optionally have type parameters (section [#type-parameter-lists]<!--3.6.1-->) that serve as placeholders for actual types to be provided when the class is referenced in type references. A class with type parameters is called a ***generic class***. The type parameters of a generic class declaration are in scope in the entire declaration and may be referenced in the *ClassHeritage* and *ClassBody*.
|
||||
|
||||
The following example introduces both a named type called 'Point' (the class type) and a named value called 'Point' (the constructor function) in the containing declaration space.
|
||||
|
||||
```TypeScript
|
||||
class Point {
|
||||
constructor(public x: number, public y: number) { }
|
||||
public length() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
||||
static origin = new Point(0, 0);
|
||||
}
|
||||
```
|
||||
|
||||
The named type 'Point' is exactly equivalent to
|
||||
|
||||
```TypeScript
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
length(): number;
|
||||
}
|
||||
```
|
||||
|
||||
The named value 'Point' is a constructor function whose type corresponds to the declaration
|
||||
|
||||
```TypeScript
|
||||
var Point: {
|
||||
new(x: number, y: number): Point;
|
||||
origin: Point;
|
||||
};
|
||||
```
|
||||
|
||||
The context in which a class is referenced distinguishes between the class type and the constructor function. For example, in the assignment statement
|
||||
|
||||
```TypeScript
|
||||
var p: Point = new Point(10, 20);
|
||||
```
|
||||
|
||||
the identifier 'Point' in the type annotation refers to the class type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object.
|
||||
|
||||
### Class Heritage Specification { #class-heritage-specification }
|
||||
|
||||
*TODO: Update this section to reflect [expressions in class extends clauses](https://github.com/Microsoft/TypeScript/pull/3516)*.
|
||||
|
||||
The heritage specification of a class consists of optional `extends` and `implements` clauses. The `extends` clause specifies the base class of the class and the `implements` clause specifies a set of interfaces for which to validate the class provides an implementation.
|
||||
|
||||
  *ClassHeritage:* *( Modified )*
|
||||
   *ClassExtendsClause<sub>opt</sub>* *ImplementsClause<sub>opt</sub>*
|
||||
|
||||
  *ClassExtendsClause:*
|
||||
   `extends`  *ClassType*
|
||||
|
||||
  *ClassType:*
|
||||
   *TypeReference*
|
||||
|
||||
  *ImplementsClause:*
|
||||
   `implements` *ClassOrInterfaceTypeList*
|
||||
|
||||
A class that includes an `extends` clause is called a ***derived class***, and the class specified in the `extends` clause is called the ***base class*** of the derived class. When a class heritage specification omits the `extends` clause, the class does not have a base class. However, as is the case with every object type, type references (section [#named-type-references]<!--3.3.1-->) to the class will appear to have the members of the global interface type named 'Object' unless those members are hidden by members with the same name in the class.
|
||||
|
||||
The following constraints must be satisfied by the class heritage specification or otherwise a compile-time error occurs:
|
||||
|
||||
* If present, the type reference specified in the `extends` clause must denote a class type. Furthermore, the *TypeName* part of the type reference is required to be a reference to the class constructor function when evaluated as an expression.
|
||||
* A class declaration may not, directly or indirectly, specify a base class that originates in the same declaration. In other words a class cannot, directly or indirectly, be a base class of itself, regardless of type arguments.
|
||||
* The this-type (section [#this-types]<!--3.6.3-->) of the declared class must be assignable (section [#assignment-compatibility]<!--3.11.4-->) to the base type reference and each of the type references listed in the `implements` clause.
|
||||
* The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures.
|
||||
|
||||
The following example illustrates a situation in which the first rule above would be violated:
|
||||
|
||||
```TypeScript
|
||||
class A { a: number; }
|
||||
|
||||
namespace Foo {
|
||||
var A = 1;
|
||||
class B extends A { b: string; }
|
||||
}
|
||||
```
|
||||
|
||||
When evaluated as an expression, the type reference 'A' in the `extends` clause doesn't reference the class constructor function of 'A' (instead it references the local variable 'A').
|
||||
|
||||
The only situation in which the last two constraints above are violated is when a class overrides one or more base class members with incompatible new members.
|
||||
|
||||
Note that because TypeScript has a structural type system, a class doesn't need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The `implements` clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type.
|
||||
|
||||
### Class Body { #class-body }
|
||||
|
||||
The class body consists of zero or more constructor or member declarations. Statements are not allowed in the body of a class—they must be placed in the constructor or in members.
|
||||
|
||||
  *ClassElement:* *( Modified )*
|
||||
   *ConstructorDeclaration*
|
||||
   *PropertyMemberDeclaration*
|
||||
   *IndexMemberDeclaration*
|
||||
|
||||
The body of class may optionally contain a single constructor declaration. Constructor declarations are described in section [#constructor-declarations]<!--8.3-->.
|
||||
|
||||
Member declarations are used to declare instance and static members of the class. Property member declarations are described in section [#property-member-declarations]<!--8.4--> and index member declarations are described in section [#index-member-declarations]<!--8.5-->.
|
||||
|
||||
## Members { #members }
|
||||
|
||||
The members of a class consist of the members introduced through member declarations in the class body and the members inherited from the base class.
|
||||
|
||||
### Instance and Static Members { #instance-and-static-members }
|
||||
|
||||
Members are either ***instance members*** or ***static members***.
|
||||
|
||||
Instance members are members of the class type (section [#class-types]<!--8.2.4-->) and its associated this-type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the this-type (section [#this-types]<!--3.6.3-->) of the class.
|
||||
|
||||
Static members are declared using the `static` modifier and are members of the constructor function type (section [#constructor-function-types]<!--8.2.5-->). Within static member functions and static member accessors, the type of `this` is the constructor function type.
|
||||
|
||||
Class type parameters cannot be referenced in static member declarations.
|
||||
|
||||
### Accessibility { #accessibility }
|
||||
|
||||
Property members have either ***public***, ***private***, or ***protected*** accessibility. The default is public accessibility, but property member declarations may include a `public`, `private`, or `protected` modifier to explicitly specify the desired accessibility.
|
||||
|
||||
Public property members can be accessed everywhere without restrictions.
|
||||
|
||||
Private property members can be accessed only within their declaring class. Specifically, a private member *M* declared in a class *C* can be accessed only within the class body of *C*.
|
||||
|
||||
Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class or a subclass thereof. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments.
|
||||
|
||||
Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object's static type to Any and accessing the member dynamically.
|
||||
|
||||
The following example demonstrates private and protected accessibility:
|
||||
|
||||
```TypeScript
|
||||
class A {
|
||||
private x: number;
|
||||
protected y: number;
|
||||
static f(a: A, b: B) {
|
||||
a.x = 1; // Ok
|
||||
b.x = 1; // Ok
|
||||
a.y = 1; // Ok
|
||||
b.y = 1; // Ok
|
||||
}
|
||||
}
|
||||
|
||||
class B extends A {
|
||||
static f(a: A, b: B) {
|
||||
a.x = 1; // Error, x only accessible within A
|
||||
b.x = 1; // Error, x only accessible within A
|
||||
a.y = 1; // Error, y must be accessed through instance of B
|
||||
b.y = 1; // Ok
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In class 'A', the accesses to 'x' are permitted because 'x' is declared in 'A', and the accesses to 'y' are permitted because both take place through an instance of 'A' or a type derived from 'A'. In class 'B', access to 'x' is not permitted, and the first access to 'y' is an error because it takes place through an instance of 'A', which is not derived from the enclosing class 'B'.
|
||||
|
||||
### Inheritance and Overriding { #inheritance-and-overriding }
|
||||
|
||||
A derived class ***inherits*** all members from its base class it doesn't ***override***. Inheritance means that a derived class implicitly contains all non-overridden members of the base class. Only public and protected property members can be overridden.
|
||||
|
||||
A property member in a derived class is said to override a property member in a base class when the derived class property member has the same name and kind (instance or static) as the base class property member. The type of an overriding property member must be assignable (section [#assignment-compatibility]<!--3.11.4-->) to the type of the overridden property member, or otherwise a compile-time error occurs.
|
||||
|
||||
Base class instance member functions can be overridden by derived class instance member functions, but not by other kinds of members.
|
||||
|
||||
Base class instance member variables and accessors can be overridden by derived class instance member variables and accessors, but not by other kinds of members.
|
||||
|
||||
Base class static property members can be overridden by derived class static property members of any kind as long as the types are compatible, as described above.
|
||||
|
||||
An index member in a derived class is said to override an index member in a base class when the derived class index member is of the same index kind (string or numeric) as the base class index member. The type of an overriding index member must be assignable (section [#assignment-compatibility]<!--3.11.4-->) to the type of the overridden index member, or otherwise a compile-time error occurs.
|
||||
|
||||
### Class Types { #class-types }
|
||||
|
||||
A class declaration declares a new named type (section [#named-types]<!--3.7-->) called a class type. Within the constructor and instance member functions of a class, the type of `this` is the this-type (section [#this-types]<!--3.6.3-->) of that class type. The class type has the following members:
|
||||
|
||||
* A property for each instance member variable declaration in the class body.
|
||||
* A property of a function type for each instance member function declaration in the class body.
|
||||
* A property for each uniquely named instance member accessor declaration in the class body.
|
||||
* A property for each constructor parameter declared with a `public`, `private`, or `protected` modifier.
|
||||
* An index signature for each instance index member declaration in the class body.
|
||||
* All base class instance property or index members that are not overridden in the class.
|
||||
|
||||
All instance property members (including those that are private or protected) of a class must satisfy the constraints implied by the index members of the class as specified in section [#index-signatures]<!--3.9.4-->.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
class A {
|
||||
public x: number;
|
||||
public f() { }
|
||||
public g(a: any) { return undefined; }
|
||||
static s: string;
|
||||
}
|
||||
|
||||
class B extends A {
|
||||
public y: number;
|
||||
public g(b: boolean) { return false; }
|
||||
}
|
||||
```
|
||||
|
||||
the class type of 'A' is equivalent to
|
||||
|
||||
```TypeScript
|
||||
interface A {
|
||||
x: number;
|
||||
f: () => void;
|
||||
g: (a: any) => any;
|
||||
}
|
||||
```
|
||||
|
||||
and the class type of 'B' is equivalent to
|
||||
|
||||
```TypeScript
|
||||
interface B {
|
||||
x: number;
|
||||
y: number;
|
||||
f: () => void;
|
||||
g: (b: boolean) => boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Note that static declarations in a class do not contribute to the class type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'.
|
||||
|
||||
### Constructor Function Types { #constructor-function-types }
|
||||
|
||||
The type of the constructor function introduced by a class declaration is called the constructor function type. The constructor function type has the following members:
|
||||
|
||||
* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
|
||||
* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
|
||||
* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
|
||||
* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
|
||||
* A property for each static member variable declaration in the class body.
|
||||
* A property of a function type for each static member function declaration in the class body.
|
||||
* A property for each uniquely named static member accessor declaration in the class body.
|
||||
* A property named 'prototype', the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
|
||||
* All base class constructor function type properties that are not overridden in the class.
|
||||
|
||||
Every class automatically contains a static property member named 'prototype', the type of which is the containing class with type Any substituted for each type parameter.
|
||||
|
||||
The example
|
||||
|
||||
```TypeScript
|
||||
class Pair<T1, T2> {
|
||||
constructor(public item1: T1, public item2: T2) { }
|
||||
}
|
||||
|
||||
class TwoArrays<T> extends Pair<T[], T[]> { }
|
||||
```
|
||||
|
||||
introduces two named types corresponding to
|
||||
|
||||
```TypeScript
|
||||
interface Pair<T1, T2> {
|
||||
item1: T1;
|
||||
item2: T2;
|
||||
}
|
||||
|
||||
interface TwoArrays<T> {
|
||||
item1: T[];
|
||||
item2: T[];
|
||||
}
|
||||
```
|
||||
|
||||
and two constructor functions corresponding to
|
||||
|
||||
```TypeScript
|
||||
var Pair: {
|
||||
new <T1, T2>(item1: T1, item2: T2): Pair<T1, T2>;
|
||||
}
|
||||
|
||||
var TwoArrays: {
|
||||
new <T>(item1: T[], item2: T[]): TwoArrays<T>;
|
||||
}
|
||||
```
|
||||
|
||||
Note that each construct signature in the constructor function types has the same type parameters as its class and returns an instantiation of its class with those type parameters passed as type arguments. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type.
|
||||
|
||||
## Constructor Declarations { #constructor-declarations }
|
||||
|
||||
A constructor declaration declares the constructor function of a class.
|
||||
|
||||
  *ConstructorDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `{` *FunctionBody* `}`
|
||||
   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;`
|
||||
|
||||
Constructor declarations that specify a body are called ***constructor implementations*** and constructor declarations without a body are called ***constructor overloads***. It is possible to specify multiple constructor overloads in a class, but a class can have at most one constructor implementation. All constructor declarations in a class must specify the same set of modifiers. Only public constructors are supported and private or protected constructors result in an error.
|
||||
|
||||
In a class with no constructor declaration, an automatic constructor is provided, as described in section [#automatic-constructors]<!--8.3.3-->.
|
||||
|
||||
When a class has constructor overloads, the overloads determine the construct signatures of the type given to the constructor function object, and the constructor implementation signature (if any) must be assignable to that type. Otherwise, the constructor implementation itself determines the construct signature. This exactly parallels the way overloads are processed in a function declaration (section [#function-overloads]<!--6.2-->).
|
||||
|
||||
When a class has both constructor overloads and a constructor implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements.
|
||||
|
||||
The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the this-type (section [#this-types]<!--3.6.3-->) of the class.
|
||||
|
||||
The type parameters of a generic class are in scope and accessible in a constructor declaration.
|
||||
|
||||
### Constructor Parameters { #constructor-parameters }
|
||||
|
||||
Similar to functions, only the constructor implementation (and not constructor overloads) can specify default value expressions for optional parameters. It is a compile-time error for such default value expressions to reference `this`. When the output target is ECMAScript 3 or 5, for each parameter with a default value, a statement that substitutes the default value for an omitted argument is included in the JavaScript generated for the constructor function.
|
||||
|
||||
A parameter of a *ConstructorImplementation* may be prefixed with a `public`, `private`, or `protected` modifier. This is called a ***parameter property declaration*** and is shorthand for declaring a property with the same name as the parameter and initializing it with the value of the parameter. For example, the declaration
|
||||
|
||||
```TypeScript
|
||||
class Point {
|
||||
constructor(public x: number, public y: number) {
|
||||
// Constructor body
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
is equivalent to writing
|
||||
|
||||
```TypeScript
|
||||
class Point {
|
||||
public x: number;
|
||||
public y: number;
|
||||
constructor(x: number, y: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
// Constructor body
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A parameter property declaration may declare an optional parameter (by including a question mark or a default value), but the property introduced by such a declaration is always considered a required property (section [#members]<!--3.3.6-->).
|
||||
|
||||
### Super Calls { #super-calls }
|
||||
|
||||
Super calls (section [#super-calls]<!--4.9.1-->) are used to call the constructor of the base class. A super call consists of the keyword `super` followed by an argument list enclosed in parentheses. For example:
|
||||
|
||||
```TypeScript
|
||||
class ColoredPoint extends Point {
|
||||
constructor(x: number, y: number, public color: string) {
|
||||
super(x, y);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Constructors of classes with no `extends` clause may not contain super calls, whereas constructors of derived classes must contain at least one super call somewhere in their function body. Super calls are not permitted outside constructors or in local functions inside constructors.
|
||||
|
||||
The first statement in the body of a constructor *must* be a super call if both of the following are true:
|
||||
|
||||
* The containing class is a derived class.
|
||||
* The constructor declares parameter properties or the containing class declares instance member variables with initializers.
|
||||
|
||||
In such a required super call, it is a compile-time error for argument expressions to reference `this`.
|
||||
|
||||
Initialization of parameter properties and instance member variables with initializers takes place immediately at the beginning of the constructor body if the class has no base class, or immediately following the super call if the class is a derived class.
|
||||
|
||||
### Automatic Constructors { #automatic-constructors }
|
||||
|
||||
If a class omits a constructor declaration, an ***automatic constructor*** is provided.
|
||||
|
||||
In a class with no `extends` clause, the automatic constructor has no parameters and performs no action other than executing the instance member variable initializers (section [#member-variable-declarations]<!--8.4.1-->), if any.
|
||||
|
||||
In a derived class, the automatic constructor has the same parameter list (and possibly overloads) as the base class constructor. The automatically provided constructor first forwards the call to the base class constructor using a call equivalent to
|
||||
|
||||
```TypeScript
|
||||
BaseClass.apply(this, arguments);
|
||||
```
|
||||
|
||||
and then executes the instance member variable initializers, if any.
|
||||
|
||||
## Property Member Declarations { #property-member-declarations }
|
||||
|
||||
Property member declarations can be member variable declarations, member function declarations, or member accessor declarations.
|
||||
|
||||
  *PropertyMemberDeclaration:*
|
||||
   *MemberVariableDeclaration*
|
||||
   *MemberFunctionDeclaration*
|
||||
   *MemberAccessorDeclaration*
|
||||
|
||||
Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class type (section [#class-types]<!--8.2.4-->), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name.
|
||||
|
||||
Member declarations with a `static` modifier are called static member declarations. Static property member declarations declare properties in the constructor function type (section [#constructor-function-types]<!--8.2.5-->), and must specify names that are unique among all static property member declarations in the containing class, with the exception that static get and set accessor declarations may pairwise specify the same name.
|
||||
|
||||
Note that the declaration spaces of instance and static property members are separate. Thus, it is possible to have instance and static property members with the same name.
|
||||
|
||||
Except for overrides, as described in section [#inheritance-and-overriding]<!--8.2.3-->, it is an error for a derived class to declare a property member with the same name and kind (instance or static) as a base class member.
|
||||
|
||||
Every class automatically contains a static property member named 'prototype', the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. It is an error to explicitly declare a static property member with the name 'prototype'.
|
||||
|
||||
Below is an example of a class containing both instance and static property member declarations:
|
||||
|
||||
```TypeScript
|
||||
class Point {
|
||||
constructor(public x: number, public y: number) { }
|
||||
public distance(p: Point) {
|
||||
var dx = this.x - p.x;
|
||||
var dy = this.y - p.y;
|
||||
return Math.sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
static origin = new Point(0, 0);
|
||||
static distance(p1: Point, p2: Point) { return p1.distance(p2); }
|
||||
}
|
||||
```
|
||||
|
||||
The class type 'Point' has the members:
|
||||
|
||||
```TypeScript
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
distance(p: Point);
|
||||
}
|
||||
```
|
||||
|
||||
and the constructor function 'Point' has a type corresponding to the declaration:
|
||||
|
||||
```TypeScript
|
||||
var Point: {
|
||||
new(x: number, y: number): Point;
|
||||
origin: Point;
|
||||
distance(p1: Point, p2: Point): number;
|
||||
}
|
||||
```
|
||||
|
||||
### Member Variable Declarations { #member-variable-declarations }
|
||||
|
||||
A member variable declaration declares an instance member variable or a static member variable.
|
||||
|
||||
  *MemberVariableDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* `;`
|
||||
|
||||
The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [#variable-statements]<!--5.2-->).
|
||||
|
||||
An instance member variable declaration introduces a member in the class type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the this-type (section [#this-types]<!--3.6.3-->) of the class.
|
||||
|
||||
A static member variable declaration introduces a property in the constructor function type and optionally initializes a property on the constructor function object. Initializers in static member variable declarations are executed once when the containing script or module is loaded.
|
||||
|
||||
Initializer expressions for instance member variables are evaluated in the scope of the class constructor body but are not permitted to reference parameters or local variables of the constructor. This effectively means that entities from outer scopes by the same name as a constructor parameter or local variable are inaccessible in initializer expressions for instance member variables.
|
||||
|
||||
Since instance member variable initializers are equivalent to assignments to properties of `this` in the constructor, the example
|
||||
|
||||
```TypeScript
|
||||
class Employee {
|
||||
public name: string;
|
||||
public address: string;
|
||||
public retired = false;
|
||||
public manager: Employee = null;
|
||||
public reports: Employee[] = [];
|
||||
}
|
||||
```
|
||||
|
||||
is equivalent to
|
||||
|
||||
```TypeScript
|
||||
class Employee {
|
||||
public name: string;
|
||||
public address: string;
|
||||
public retired: boolean;
|
||||
public manager: Employee;
|
||||
public reports: Employee[];
|
||||
constructor() {
|
||||
this.retired = false;
|
||||
this.manager = null;
|
||||
this.reports = [];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Member Function Declarations { #member-function-declarations }
|
||||
|
||||
A member function declaration declares an instance member function or a static member function.
|
||||
|
||||
  *MemberFunctionDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `{` *FunctionBody* `}`
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;`
|
||||
|
||||
A member function declaration is processed in the same manner as an ordinary function declaration (section [#functions]<!--6-->), except that in a member function `this` has a known type.
|
||||
|
||||
All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static).
|
||||
|
||||
An instance member function declaration declares a property in the class type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the this-type (section [#this-types]<!--3.6.3-->) of the class.
|
||||
|
||||
A static member function declaration declares a property in the constructor function type and assigns a function object to a property on the constructor function object. In the body of a static member function declaration, the type of `this` is the constructor function type.
|
||||
|
||||
A member function can access overridden base class members using a super property access (section [#super-property-access]<!--4.9.2-->). For example
|
||||
|
||||
```TypeScript
|
||||
class Point {
|
||||
constructor(public x: number, public y: number) { }
|
||||
public toString() {
|
||||
return "x=" + this.x + " y=" + this.y;
|
||||
}
|
||||
}
|
||||
|
||||
class ColoredPoint extends Point {
|
||||
constructor(x: number, y: number, public color: string) {
|
||||
super(x, y);
|
||||
}
|
||||
public toString() {
|
||||
return super.toString() + " color=" + this.color;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In a static member function, `this` represents the constructor function object on which the static member function was invoked. Thus, a call to 'new this()' may actually invoke a derived class constructor:
|
||||
|
||||
```TypeScript
|
||||
class A {
|
||||
a = 1;
|
||||
static create() {
|
||||
return new this();
|
||||
}
|
||||
}
|
||||
|
||||
class B extends A {
|
||||
b = 2;
|
||||
}
|
||||
|
||||
var x = A.create(); // new A()
|
||||
var y = B.create(); // new B()
|
||||
```
|
||||
|
||||
Note that TypeScript doesn't require or verify that derived constructor functions are subtypes of base constructor functions. In other words, changing the declaration of 'B' to
|
||||
|
||||
```TypeScript
|
||||
class B extends A {
|
||||
constructor(public b: number) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
does not cause errors in the example, even though the call to the constructor from the 'create' function doesn't specify an argument (thus giving the value 'undefined' to 'b').
|
||||
|
||||
### Member Accessor Declarations { #member-accessor-declarations }
|
||||
|
||||
A member accessor declaration declares an instance member accessor or a static member accessor.
|
||||
|
||||
  *MemberAccessorDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *GetAccessor*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *SetAccessor*
|
||||
|
||||
Get and set accessors are processed in the same manner as in an object literal (section [#object-literals]<!--4.5-->), except that a contextual type is never available in a member accessor declaration.
|
||||
|
||||
Accessors for the same member name must specify the same accessibility.
|
||||
|
||||
An instance member accessor declaration declares a property in the class type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the this-type (section [#this-types]<!--3.6.3-->) of the class.
|
||||
|
||||
A static member accessor declaration declares a property in the constructor function type and defines a property on the constructor function object of the class with a get or set accessor. In the body of a static member accessor declaration, the type of `this` is the constructor function type.
|
||||
|
||||
Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [#classes-without-extends-clauses]<!--8.7.1-->.
|
||||
|
||||
### Dynamic Property Declarations { #dynamic-property-declarations }
|
||||
|
||||
If the *PropertyName* of a property member declaration is a computed property name that doesn't denote a well-known symbol ([#computed-property-names]<!--2.2.3-->), the construct is considered a ***dynamic property declaration***. The following rules apply to dynamic property declarations:
|
||||
|
||||
* A dynamic property declaration does not introduce a property in the class type or constructor function type.
|
||||
* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type.
|
||||
* The name associated with a dynamic property declarations is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type.
|
||||
|
||||
## Index Member Declarations { #index-member-declarations }
|
||||
|
||||
An index member declaration introduces an index signature (section [#index-signatures]<!--3.9.4-->) in the class type.
|
||||
|
||||
  *IndexMemberDeclaration:*
|
||||
   *IndexSignature* `;`
|
||||
|
||||
Index member declarations have no body and cannot specify an accessibility modifier.
|
||||
|
||||
A class declaration can have at most one string index member declaration and one numeric index member declaration. All instance property members of a class must satisfy the constraints implied by the index members of the class as specified in section [#index-signatures]<!--3.9.4-->.
|
||||
|
||||
It is not possible to declare index members for the static side of a class.
|
||||
|
||||
Note that it is seldom meaningful to include a string index signature in a class because it constrains all instance properties of the class. However, numeric index signatures can be useful to control the element type when a class is used in an array-like manner.
|
||||
|
||||
## Decorators { #decorators }
|
||||
|
||||
*TODO: Document [decorators](https://github.com/Microsoft/TypeScript/issues/2249)*.
|
||||
|
||||
## Code Generation { #code-generation }
|
||||
|
||||
When the output target is ECMAScript 2015 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section.
|
||||
|
||||
### Classes Without Extends Clauses { #classes-without-extends-clauses }
|
||||
|
||||
A class with no `extends` clause generates JavaScript equivalent to the following:
|
||||
|
||||
```TypeScript
|
||||
var <ClassName> = (function () {
|
||||
function <ClassName>(<ConstructorParameters>) {
|
||||
<DefaultValueAssignments>
|
||||
<ParameterPropertyAssignments>
|
||||
<MemberVariableAssignments>
|
||||
<ConstructorStatements>
|
||||
}
|
||||
<MemberFunctionStatements>
|
||||
<StaticVariableAssignments>
|
||||
return <ClassName>;
|
||||
})();
|
||||
```
|
||||
|
||||
*ClassName* is the name of the class.
|
||||
|
||||
*ConstructorParameters* is a comma separated list of the constructor's parameter names.
|
||||
|
||||
*DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [#code-generation]<!--6.6-->.
|
||||
|
||||
*ParameterPropertyAssignments* is a sequence of assignments, one for each parameter property declaration in the constructor, in order they are declared, of the form
|
||||
|
||||
```TypeScript
|
||||
this.<ParameterName> = <ParameterName>;
|
||||
```
|
||||
|
||||
where *ParameterName* is the name of a parameter property.
|
||||
|
||||
*MemberVariableAssignments* is a sequence of assignments, one for each instance member variable declaration with an initializer, in the order they are declared, of the form
|
||||
|
||||
```TypeScript
|
||||
this.<MemberName> = <InitializerExpression>;
|
||||
```
|
||||
|
||||
where *MemberName* is the name of the member variable and *InitializerExpression* is the code generated for the initializer expression.
|
||||
|
||||
*ConstructorStatements* is the code generated for the statements specified in the constructor body.
|
||||
|
||||
*MemberFunctionStatements* is a sequence of statements, one for each member function declaration or member accessor declaration, in the order they are declared.
|
||||
|
||||
An instance member function declaration generates a statement of the form
|
||||
|
||||
```TypeScript
|
||||
<ClassName>.prototype.<MemberName> = function (<FunctionParameters>) {
|
||||
<DefaultValueAssignments>
|
||||
<FunctionStatements>
|
||||
}
|
||||
```
|
||||
|
||||
and static member function declaration generates a statement of the form
|
||||
|
||||
```TypeScript
|
||||
<ClassName>.<MemberName> = function (<FunctionParameters>) {
|
||||
<DefaultValueAssignments>
|
||||
<FunctionStatements>
|
||||
}
|
||||
```
|
||||
|
||||
where *MemberName* is the name of the member function, and *FunctionParameters*, *DefaultValueAssignments*, and *FunctionStatements* correspond to those generated for a regular function declaration, as described in section [#code-generation]<!--6.6-->.
|
||||
|
||||
A get or set instance member accessor declaration, or a pair of get and set instance member accessor declarations with the same name, generates a statement of the form
|
||||
|
||||
```TypeScript
|
||||
Object.defineProperty(<ClassName>.prototype, "<MemberName>", {
|
||||
get: function () {
|
||||
<GetAccessorStatements>
|
||||
},
|
||||
set: function (<ParameterName>) {
|
||||
<SetAccessorStatements>
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
```
|
||||
|
||||
and a get or set static member accessor declaration, or a pair of get and set static member accessor declarations with the same name, generates a statement of the form
|
||||
|
||||
```TypeScript
|
||||
Object.defineProperty(<ClassName>, "<MemberName>", {
|
||||
get: function () {
|
||||
<GetAccessorStatements>
|
||||
},
|
||||
set: function (<ParameterName>) {
|
||||
<SetAccessorStatements>
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
```
|
||||
|
||||
where *MemberName* is the name of the member accessor, *GetAccessorStatements* is the code generated for the statements in the get acessor's function body, *ParameterName* is the name of the set accessor parameter, and *SetAccessorStatements* is the code generated for the statements in the set accessor's function body. The 'get' property is included only if a get accessor is declared and the 'set' property is included only if a set accessor is declared.
|
||||
|
||||
*StaticVariableAssignments* is a sequence of statements, one for each static member variable declaration with an initializer, in the order they are declared, of the form
|
||||
|
||||
```TypeScript
|
||||
<ClassName>.<MemberName> = <InitializerExpression>;
|
||||
```
|
||||
|
||||
where *MemberName* is the name of the static variable, and *InitializerExpression* is the code generated for the initializer expression.
|
||||
|
||||
### Classes With Extends Clauses { #classes-with-extends-clauses }
|
||||
|
||||
A class with an `extends` clause generates JavaScript equivalent to the following:
|
||||
|
||||
```TypeScript
|
||||
var <ClassName> = (function (_super) {
|
||||
__extends(<ClassName>, _super);
|
||||
function <ClassName>(<ConstructorParameters>) {
|
||||
<DefaultValueAssignments>
|
||||
<SuperCallStatement>
|
||||
<ParameterPropertyAssignments>
|
||||
<MemberVariableAssignments>
|
||||
<ConstructorStatements>
|
||||
}
|
||||
<MemberFunctionStatements>
|
||||
<StaticVariableAssignments>
|
||||
return <ClassName>;
|
||||
})(<BaseClassName>);
|
||||
```
|
||||
|
||||
In addition, the '__extends' function below is emitted at the beginning of the JavaScript source file. It copies all properties from the base constructor function object to the derived constructor function object (in order to inherit static members), and appropriately establishes the 'prototype' property of the derived constructor function object.
|
||||
|
||||
```TypeScript
|
||||
var __extends = this.__extends || function(d, b) {
|
||||
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
||||
function f() { this.constructor = d; }
|
||||
f.prototype = b.prototype;
|
||||
d.prototype = new f();
|
||||
}
|
||||
```
|
||||
|
||||
*BaseClassName* is the class name specified in the `extends` clause.
|
||||
|
||||
If the class has no explicitly declared constructor, the *SuperCallStatement* takes the form
|
||||
|
||||
```TypeScript
|
||||
_super.apply(this, arguments);
|
||||
```
|
||||
|
||||
Otherwise the *SuperCallStatement* is present if the constructor function is required to start with a super call, as discussed in section [#super-calls]<!--8.3.2-->, and takes the form
|
||||
|
||||
```TypeScript
|
||||
_super.call(this, <SuperCallArguments>)
|
||||
```
|
||||
|
||||
where *SuperCallArguments* is the argument list specified in the super call. Note that this call precedes the code generated for parameter properties and member variables with initializers. Super calls elsewhere in the constructor generate similar code, but the code generated for such calls will be part of the *ConstructorStatements* section.
|
||||
|
||||
A super property access in the constructor, an instance member function, or an instance member accessor generates JavaScript equivalent to
|
||||
|
||||
```TypeScript
|
||||
_super.prototype.<PropertyName>
|
||||
```
|
||||
|
||||
where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to
|
||||
|
||||
```TypeScript
|
||||
_super.prototype.<PropertyName>.call(this, <Arguments>)
|
||||
```
|
||||
|
||||
where Arguments is the code generated for the argument list specified in the function call.
|
||||
|
||||
A super property access in a static member function or a static member accessor generates JavaScript equivalent to
|
||||
|
||||
```TypeScript
|
||||
_super.<PropertyName>
|
||||
```
|
||||
|
||||
where *PropertyName* is the name of the referenced base class property. When the super property access appears in a function call, the generated JavaScript is equivalent to
|
||||
|
||||
```TypeScript
|
||||
_super.<PropertyName>.call(this, <Arguments>)
|
||||
```
|
||||
|
||||
where Arguments is the code generated for the argument list specified in the function call.
|
||||
|
||||
<br/>
|
||||
|
||||
169
doc/spec/Enums.md
Normal file
169
doc/spec/Enums.md
Normal file
@@ -0,0 +1,169 @@
|
||||
# Enums { #enums }
|
||||
|
||||
An enum type is a distinct subtype of the Number primitive type with an associated set of named constants that define the possible values of the enum type.
|
||||
|
||||
## Enum Declarations { #enum-declarations }
|
||||
|
||||
An enum declaration declares an ***enum type*** and an ***enum object***.
|
||||
|
||||
  *EnumDeclaration:*
|
||||
   `const`*<sub>opt</sub>* `enum` *BindingIdentifier* `{` *EnumBody<sub>opt</sub>* `}`
|
||||
|
||||
An *EnumDeclaration* introduces a named type (the enum type) and a named value (the enum object) in the containing declaration space. The enum type is a distinct subtype of the Number primitive type. The enum object is a value of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object's type furthermore includes a numeric index signature with the signature '[x: number]: string'.
|
||||
|
||||
The *BindingIdentifier* of an enum declaration may not be one of the predefined type names (section [#predefined-types]<!--3.8.1-->).
|
||||
|
||||
When an enum declaration includes a `const` modifier it is said to be a constant enum declaration. The members of a constant enum declaration must all have constant values that can be computed at compile time. Constant enum declarations are discussed in section [#constant-enum-declarations]<!--9.4-->.
|
||||
|
||||
The example
|
||||
|
||||
```TypeScript
|
||||
enum Color { Red, Green, Blue }
|
||||
```
|
||||
|
||||
declares a subtype of the Number primitive type called 'Color' and introduces a variable 'Color' with a type that corresponds to the declaration
|
||||
|
||||
```TypeScript
|
||||
var Color: {
|
||||
[x: number]: string;
|
||||
Red: Color;
|
||||
Green: Color;
|
||||
Blue: Color;
|
||||
};
|
||||
```
|
||||
|
||||
The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [#code-generation]<!--9.5-->. The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example
|
||||
|
||||
```TypeScript
|
||||
var c = Color.Red;
|
||||
console.log(Color[c]); // Outputs "Red"
|
||||
```
|
||||
|
||||
## Enum Members { #enum-members }
|
||||
|
||||
The body of an enum declaration defines zero or more enum members which are the named values of the enum type. Each enum member has an associated numeric value of the primitive type introduced by the enum declaration.
|
||||
|
||||
  *EnumBody:*
|
||||
   *EnumMemberList* `,`*<sub>opt</sub>*
|
||||
|
||||
  *EnumMemberList:*
|
||||
   *EnumMember*
|
||||
   *EnumMemberList* `,` *EnumMember*
|
||||
|
||||
  *EnumMember:*
|
||||
   *PropertyName*
|
||||
   *PropertyName* = *EnumValue*
|
||||
|
||||
  *EnumValue:*
|
||||
   *AssignmentExpression*
|
||||
|
||||
The *PropertyName* of an enum member cannot be a computed property name ([#computed-property-names]<!--2.2.3-->).
|
||||
|
||||
Enum members are either ***constant members*** or ***computed members***. Constant members have known constant values that are substituted in place of references to the members in the generated JavaScript code. Computed members have values that are computed at run-time and not known at compile-time. No substitution is performed for references to computed members.
|
||||
|
||||
An enum member is classified as follows:
|
||||
|
||||
* If the member declaration specifies no value, the member is considered a constant enum member. If the member is the first member in the enum declaration, it is assigned the value zero. Otherwise, it is assigned the value of the immediately preceding member plus one, and an error occurs if the immediately preceding member is not a constant enum member.
|
||||
* If the member declaration specifies a value that can be classified as a constant enum expression (as defined below), the member is considered a constant enum member.
|
||||
* Otherwise, the member is considered a computed enum member.
|
||||
|
||||
Enum value expressions must be of type Any, the Number primitive type, or the enum type itself.
|
||||
|
||||
A ***constant enum expression*** is a subset of the expression grammar that can be evaluated fully at compile time. An expression is considered a constant enum expression if it is one of the following:
|
||||
|
||||
* A numeric literal.
|
||||
* An identifier or property access that denotes a previously declared member in the same constant enum declaration.
|
||||
* A parenthesized constant enum expression.
|
||||
* A +, –, or ~ unary operator applied to a constant enum expression.
|
||||
* A +, –, *, /, %, <<, >>, >>>, &, ^, or | operator applied to two constant enum expressions.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
enum Test {
|
||||
A,
|
||||
B,
|
||||
C = Math.floor(Math.random() * 1000),
|
||||
D = 10,
|
||||
E
|
||||
}
|
||||
```
|
||||
|
||||
'A', 'B', 'D', and 'E' are constant members with values 0, 1, 10, and 11 respectively, and 'C' is a computed member.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
enum Style {
|
||||
None = 0,
|
||||
Bold = 1,
|
||||
Italic = 2,
|
||||
Underline = 4,
|
||||
Emphasis = Bold | Italic,
|
||||
Hyperlink = Bold | Underline
|
||||
}
|
||||
```
|
||||
|
||||
all members are constant members. Note that enum member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values.
|
||||
|
||||
## Declaration Merging { #declaration-merging }
|
||||
|
||||
Enums are "open-ended" and enum declarations with the same qualified name relative to a common root (as defined in section [#declarations]<!--2.3-->) define a single enum type and contribute to a single enum object.
|
||||
|
||||
It isn't possible for one enum declaration to continue the automatic numbering sequence of another, and when an enum type has multiple declarations, only one declaration is permitted to omit a value for the first member.
|
||||
|
||||
When enum declarations are merged, they must either all specify a `const` modifier or all specify no `const` modifier.
|
||||
|
||||
## Constant Enum Declarations { #constant-enum-declarations }
|
||||
|
||||
An enum declaration that specifies a `const` modifier is a ***constant enum declaration***. In a constant enum declaration, all members must have constant values and it is an error for a member declaration to specify an expression that isn't classified as a constant enum expression.
|
||||
|
||||
Unlike regular enum declarations, constant enum declarations are completely erased in the emitted JavaScript code. For this reason, it is an error to reference a constant enum object in any other context than a property access that selects one of the enum's members. For example:
|
||||
|
||||
```TypeScript
|
||||
const enum Comparison {
|
||||
LessThan = -1,
|
||||
EqualTo = 0,
|
||||
GreaterThan = 1
|
||||
}
|
||||
|
||||
var x = Comparison.EqualTo; // Ok, replaced with 0 in emitted code
|
||||
var y = Comparison[Comparison.EqualTo]; // Error
|
||||
var z = Comparison; // Error
|
||||
```
|
||||
|
||||
The entire const enum declaration is erased in the emitted JavaScript code. Thus, the only permitted references to the enum object are those that are replaced with an enum member value.
|
||||
|
||||
## Code Generation { #code-generation }
|
||||
|
||||
An enum declaration generates JavaScript equivalent to the following:
|
||||
|
||||
```TypeScript
|
||||
var <EnumName>;
|
||||
(function (<EnumName>) {
|
||||
<EnumMemberAssignments>
|
||||
})(<EnumName>||(<EnumName>={}));
|
||||
```
|
||||
|
||||
*EnumName* is the name of the enum.
|
||||
|
||||
*EnumMemberAssignments* is a sequence of assignments, one for each enum member, in order they are declared, of the form
|
||||
|
||||
```TypeScript
|
||||
<EnumName>[<EnumName>["<MemberName>"] = <Value>] = "<MemberName>";
|
||||
```
|
||||
|
||||
where *MemberName* is the name of the enum member and *Value* is the assigned constant value or the code generated for the computed value expression.
|
||||
|
||||
For example, the 'Color' enum example from section [#enum-declarations]<!--9.1--> generates the following JavaScript:
|
||||
|
||||
```TypeScript
|
||||
var Color;
|
||||
(function (Color) {
|
||||
Color[Color["Red"] = 0] = "Red";
|
||||
Color[Color["Green"] = 1] = "Green";
|
||||
Color[Color["Blue"] = 2] = "Blue";
|
||||
})(Color||(Color={}));
|
||||
```
|
||||
|
||||
<br/>
|
||||
1015
doc/spec/Expressions.md
Normal file
1015
doc/spec/Expressions.md
Normal file
File diff suppressed because it is too large
Load Diff
21
doc/spec/Front Matter.md
Normal file
21
doc/spec/Front Matter.md
Normal file
@@ -0,0 +1,21 @@
|
||||
Title : TypeScript Language Specification
|
||||
Sub Title : Version 2.7
|
||||
Author : Anders Hejlsberg
|
||||
Author : Steve Lucco
|
||||
Author : Daniel Rosenwasser
|
||||
Author : Nathan Shively-Sanders
|
||||
name-contents: Table of Contents
|
||||
|
||||
[TITLE]
|
||||
|
||||
<br/>
|
||||
|
||||
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](http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0).
|
||||
|
||||
TypeScript is a trademark of Microsoft Corporation.
|
||||
|
||||
<br/>
|
||||
|
||||
[TOC]
|
||||
|
||||
<br/>
|
||||
251
doc/spec/Functions.md
Normal file
251
doc/spec/Functions.md
Normal file
@@ -0,0 +1,251 @@
|
||||
|
||||
# Functions { #functions }
|
||||
|
||||
TypeScript extends JavaScript functions to include type parameters, parameter and return type annotations, overloads, default parameter values, and rest parameters.
|
||||
|
||||
## Function Declarations { #function-declarations }
|
||||
|
||||
Function declarations are extended to permit the function body to be omitted in overload declarations.
|
||||
|
||||
  *FunctionDeclaration:* *( Modified )*
|
||||
   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}`
|
||||
   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `;`
|
||||
|
||||
A *FunctionDeclaration* introduces a named value of a function type in the containing declaration space. The *BindingIdentifier* is optional only when the function declaration occurs in an export default declaration (section [#export-default-declarations]<!--11.3.4.2-->).
|
||||
|
||||
Function declarations that specify a body are called ***function implementations*** and function declarations without a body are called ***function overloads***. It is possible to specify multiple overloads for the same function (i.e. for the same name in the same declaration space), but a function can have at most one implementation. All declarations for the same function must specify the same set of modifiers (i.e. the same combination of `declare`, `export`, and `default`).
|
||||
|
||||
When a function has overload declarations, the overloads determine the call signatures of the type given to the function object and the function implementation signature (if any) must be assignable to that type. Otherwise, the function implementation itself determines the call signature.
|
||||
|
||||
When a function has both overloads and an implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements.
|
||||
|
||||
## Function Overloads { #function-overloads }
|
||||
|
||||
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 [#function-calls]<!--4.15-->.
|
||||
|
||||
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.
|
||||
|
||||
The following is an example of a function with overloads.
|
||||
|
||||
```TypeScript
|
||||
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 === "string") {
|
||||
// handle string case
|
||||
}
|
||||
else {
|
||||
// handle map 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
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
## Function Implementations { #function-implementations }
|
||||
|
||||
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, if *f* is a contextually typed function expression (section [#function-expressions]<!--4.10-->), the inferred return type is the union type (section [#union-types]<!--3.4-->) of the types of the return statement expressions in the function body, ignoring return statements with no expressions.
|
||||
* Otherwise, the inferred return type is the first of the types of the return statement expressions in the function body that is a supertype (section [#subtypes-and-supertypes]<!--3.11.3-->) of each of the others, ignoring return statements with no expressions. A compile-time error occurs if no return statement expression has a type that is a supertype of each of the others.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
An explicitly typed function whose return type isn't the Void type, the Any type, or a union type containing the Void or Any type as a constituent must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement.
|
||||
|
||||
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. When a parameter declaration includes both a type annotation and an initializer, the initializer expression is contextually typed (section [#contextually-typed-expressions]<!--4.23-->) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. When a parameter declaration has no type annotation but includes an initializer, the type of the parameter is the widened form (section [#widened-types]<!--3.12-->) of the type of the initializer expression.
|
||||
|
||||
Initializer expressions are evaluated in the scope of the function body but are not permitted to reference local variables and are only permitted to access parameters that are declared to the left of the parameter they initialize, unless the parameter reference occurs in a nested function expression.
|
||||
|
||||
When the output target is ECMAScript 3 or 5, 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 [#code-generation]<!--6.6-->. The example
|
||||
|
||||
```TypeScript
|
||||
function strange(x: number, y = x * 2, z = x + y) {
|
||||
return z;
|
||||
}
|
||||
```
|
||||
|
||||
generates JavaScript that is equivalent to
|
||||
|
||||
```TypeScript
|
||||
function strange(x, y, z) {
|
||||
if (y === void 0) { y = x * 2; }
|
||||
if (z === void 0) { z = x + y; }
|
||||
return z;
|
||||
}
|
||||
```
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
var x = 1;
|
||||
function f(a = x) {
|
||||
var x = "hello";
|
||||
}
|
||||
```
|
||||
|
||||
the local variable 'x' is in scope in the parameter initializer (thus hiding the outer 'x'), but it is an error to reference it because it will always be uninitialized at the time the parameter initializer is evaluated.
|
||||
|
||||
## Destructuring Parameter Declarations { #destructuring-parameter-declarations }
|
||||
|
||||
Parameter declarations can specify binding patterns (section [#parameter-list]<!--3.9.2.2-->) and are then called ***destructuring parameter declarations***. Similar to a destructuring variable declaration (section [#destructuring-variable-declarations]<!--5.2.2-->), a destructuring parameter declaration introduces zero or more named locals and initializes them with values extracted from properties or elements of the object or array passed as an argument for the parameter.
|
||||
|
||||
The type of local introduced in a destructuring parameter declaration is determined in the same manner as a local introduced by a destructuring variable declaration, except the type *T* associated with a destructuring parameter declaration is determined as follows:
|
||||
|
||||
* If the declaration includes a type annotation, *T* is that type.
|
||||
* If the declaration occurs in a function expression for which a contextual signature is available (section [#function-expressions]<!--4.10-->), *T* is the type obtained from the contextual signature.
|
||||
* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [#widened-types]<!--3.12-->) of the type of the initializer expression.
|
||||
* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [#implied-type]<!--5.2.3-->).
|
||||
* Otherwise, if the parameter is a rest parameter, *T* is `any[]`.
|
||||
* Otherwise, *T* is `any`.
|
||||
|
||||
When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations.
|
||||
|
||||
The example
|
||||
|
||||
```TypeScript
|
||||
function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) {
|
||||
// Draw text
|
||||
}
|
||||
```
|
||||
|
||||
declares a function `drawText` that takes a single parameter of the type
|
||||
|
||||
```TypeScript
|
||||
{ text?: string; location?: [number, number]; bold?: boolean; }
|
||||
```
|
||||
|
||||
When the output target is ECMAScript 3 or 5, the function is rewritten to
|
||||
|
||||
```TypeScript
|
||||
function drawText(_a) {
|
||||
var _b = _a.text,
|
||||
text = _b === void 0 ? "" : _b,
|
||||
_c = _a.location,
|
||||
_d = _c === void 0 ? [0, 0] : _c,
|
||||
x = _d[0],
|
||||
y = _d[1],
|
||||
_e = _a.bold,
|
||||
bold = _e === void 0 ? false : _e;
|
||||
// Draw text
|
||||
}
|
||||
```
|
||||
|
||||
Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. Type annotations must instead be written on the top-level parameter declaration. For example
|
||||
|
||||
```TypeScript
|
||||
interface DrawTextInfo {
|
||||
text?: string;
|
||||
location?: [number, number];
|
||||
bold?: boolean;
|
||||
}
|
||||
|
||||
function drawText({ text, location: [x, y], bold }: DrawTextInfo) {
|
||||
// Draw text
|
||||
}
|
||||
```
|
||||
|
||||
## Generic Functions { #generic-functions }
|
||||
|
||||
A function implementation may include type parameters in its signature (section [#type-parameters]<!--3.9.2.1-->) 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:
|
||||
|
||||
```TypeScript
|
||||
interface Comparable {
|
||||
localeCompare(other: any): number;
|
||||
}
|
||||
|
||||
function compare<T extends Comparable>(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' and therefore have a 'compareTo' member. This is described further in section [#type-parameter-lists]<!--3.6.1-->.
|
||||
|
||||
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 [#type-argument-inference]<!--4.15.2-->) from the types of the regular arguments in the call. In the example
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
## Code Generation { #code-generation }
|
||||
|
||||
A function declaration generates JavaScript code that is equivalent to:
|
||||
|
||||
```TypeScript
|
||||
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
|
||||
|
||||
```TypeScript
|
||||
if (<Parameter> === void 0) { <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.
|
||||
|
||||
## Generator Functions { #generator-functions }
|
||||
|
||||
*TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*.
|
||||
|
||||
## Asynchronous Functions { #asynchronous-functions }
|
||||
|
||||
*TODO: Document [asynchronous functions](https://github.com/Microsoft/TypeScript/issues/1664)*.
|
||||
|
||||
## Type Guard Functions { #type-guard-functions }
|
||||
|
||||
*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007), including [this type predicates](https://github.com/Microsoft/TypeScript/pull/5906)*.
|
||||
|
||||
<br/>
|
||||
|
||||
587
doc/spec/Grammar.md
Normal file
587
doc/spec/Grammar.md
Normal file
@@ -0,0 +1,587 @@
|
||||
# Grammar { #grammar }
|
||||
|
||||
This appendix contains a summary of the grammar found in the main document. As described in section [#grammar-conventions]<!--2.1-->, the TypeScript grammar is a superset of the grammar defined in the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar.
|
||||
|
||||
## Types { #grammar-types }
|
||||
|
||||
  *TypeParameters:*
|
||||
   `<` *TypeParameterList* `>`
|
||||
|
||||
  *TypeParameterList:*
|
||||
   *TypeParameter*
|
||||
   *TypeParameterList* `,` *TypeParameter*
|
||||
|
||||
  *TypeParameter:*
|
||||
   *BindingIdentifier* *Constraint<sub>opt</sub>*
|
||||
|
||||
  *Constraint:*
|
||||
   `extends` *Type*
|
||||
|
||||
  *TypeArguments:*
|
||||
   `<` *TypeArgumentList* `>`
|
||||
|
||||
  *TypeArgumentList:*
|
||||
   *TypeArgument*
|
||||
   *TypeArgumentList* `,` *TypeArgument*
|
||||
|
||||
  *TypeArgument:*
|
||||
   *Type*
|
||||
|
||||
  *Type:*
|
||||
   *UnionOrIntersectionOrPrimaryType*
|
||||
   *FunctionType*
|
||||
   *ConstructorType*
|
||||
|
||||
  *UnionOrIntersectionOrPrimaryType:*
|
||||
   *UnionType*
|
||||
   *IntersectionOrPrimaryType*
|
||||
|
||||
  *IntersectionOrPrimaryType:*
|
||||
   *IntersectionType*
|
||||
   *PrimaryType*
|
||||
|
||||
  *PrimaryType:*
|
||||
   *ParenthesizedType*
|
||||
   *PredefinedType*
|
||||
   *TypeReference*
|
||||
   *ObjectType*
|
||||
   *ArrayType*
|
||||
   *TupleType*
|
||||
   *TypeQuery*
|
||||
   *ThisType*
|
||||
|
||||
  *ParenthesizedType:*
|
||||
   `(` *Type* `)`
|
||||
|
||||
  *PredefinedType:*
|
||||
   `any`
|
||||
   `number`
|
||||
   `boolean`
|
||||
   `string`
|
||||
   `symbol`
|
||||
   `void`
|
||||
|
||||
  *TypeReference:*
|
||||
   *TypeName* *[no LineTerminator here]* *TypeArguments<sub>opt</sub>*
|
||||
|
||||
  *TypeName:*
|
||||
   *IdentifierReference*
|
||||
   *NamespaceName* `.` *IdentifierReference*
|
||||
|
||||
  *NamespaceName:*
|
||||
   *IdentifierReference*
|
||||
   *NamespaceName* `.` *IdentifierReference*
|
||||
|
||||
  *ObjectType:*
|
||||
   `{` *TypeBody<sub>opt</sub>* `}`
|
||||
|
||||
  *TypeBody:*
|
||||
   *TypeMemberList* `;`*<sub>opt</sub>*
|
||||
   *TypeMemberList* `,`*<sub>opt</sub>*
|
||||
|
||||
  *TypeMemberList:*
|
||||
   *TypeMember*
|
||||
   *TypeMemberList* `;` *TypeMember*
|
||||
   *TypeMemberList* `,` *TypeMember*
|
||||
|
||||
  *TypeMember:*
|
||||
   *PropertySignature*
|
||||
   *CallSignature*
|
||||
   *ConstructSignature*
|
||||
   *IndexSignature*
|
||||
   *MethodSignature*
|
||||
|
||||
  *ArrayType:*
|
||||
   *PrimaryType* *[no LineTerminator here]* `[` `]`
|
||||
|
||||
  *TupleType:*
|
||||
   `[` *TupleElementTypes* `]`
|
||||
|
||||
  *TupleElementTypes:*
|
||||
   *TupleElementType*
|
||||
   *TupleElementTypes* `,` *TupleElementType*
|
||||
|
||||
  *TupleElementType:*
|
||||
   *Type*
|
||||
|
||||
  *UnionType:*
|
||||
   *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType*
|
||||
|
||||
  *IntersectionType:*
|
||||
   *IntersectionOrPrimaryType* `&` *PrimaryType*
|
||||
|
||||
  *FunctionType:*
|
||||
   *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` `=>` *Type*
|
||||
|
||||
  *ConstructorType:*
|
||||
   `new` *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` `=>` *Type*
|
||||
|
||||
  *TypeQuery:*
|
||||
   `typeof` *TypeQueryExpression*
|
||||
|
||||
  *TypeQueryExpression:*
|
||||
   *IdentifierReference*
|
||||
   *TypeQueryExpression* `.` *IdentifierName*
|
||||
|
||||
  *ThisType:*
|
||||
   `this`
|
||||
|
||||
  *PropertySignature:*
|
||||
   *PropertyName* `?`*<sub>opt</sub>* *TypeAnnotation<sub>opt</sub>*
|
||||
|
||||
  *PropertyName:*
|
||||
   *IdentifierName*
|
||||
   *StringLiteral*
|
||||
   *NumericLiteral*
|
||||
|
||||
  *TypeAnnotation:*
|
||||
   `:` *Type*
|
||||
|
||||
  *CallSignature:*
|
||||
   *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` *TypeAnnotation<sub>opt</sub>*
|
||||
|
||||
  *ParameterList:*
|
||||
   *RequiredParameterList*
|
||||
   *OptionalParameterList*
|
||||
   *RestParameter*
|
||||
   *RequiredParameterList* `,` *OptionalParameterList*
|
||||
   *RequiredParameterList* `,` *RestParameter*
|
||||
   *OptionalParameterList* `,` *RestParameter*
|
||||
   *RequiredParameterList* `,` *OptionalParameterList* `,` *RestParameter*
|
||||
|
||||
  *RequiredParameterList:*
|
||||
   *RequiredParameter*
|
||||
   *RequiredParameterList* `,` *RequiredParameter*
|
||||
|
||||
  *RequiredParameter:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>*
|
||||
   *BindingIdentifier* `:` *StringLiteral*
|
||||
|
||||
  *AccessibilityModifier:*
|
||||
   `public`
|
||||
   `private`
|
||||
   `protected`
|
||||
|
||||
  *BindingIdentifierOrPattern:*
|
||||
   *BindingIdentifier*
|
||||
   *BindingPattern*
|
||||
|
||||
  *OptionalParameterList:*
|
||||
   *OptionalParameter*
|
||||
   *OptionalParameterList* `,` *OptionalParameter*
|
||||
|
||||
  *OptionalParameter:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* `?` *TypeAnnotation<sub>opt</sub>*
|
||||
   *AccessibilityModifier<sub>opt</sub>* *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* *Initializer*
|
||||
   *BindingIdentifier* `?` `:` *StringLiteral*
|
||||
|
||||
  *RestParameter:*
|
||||
   `...` *BindingIdentifier* *TypeAnnotation<sub>opt</sub>*
|
||||
|
||||
  *ConstructSignature:*
|
||||
   `new` *TypeParameters<sub>opt</sub>* `(` *ParameterList<sub>opt</sub>* `)` *TypeAnnotation<sub>opt</sub>*
|
||||
|
||||
  *IndexSignature:*
|
||||
   `[` *BindingIdentifier* `:` `string` `]` *TypeAnnotation*
|
||||
   `[` *BindingIdentifier* `:` `number` `]` *TypeAnnotation*
|
||||
|
||||
  *MethodSignature:*
|
||||
   *PropertyName* `?`*<sub>opt</sub>* *CallSignature*
|
||||
|
||||
  *TypeAliasDeclaration:*
|
||||
   `type` *BindingIdentifier* *TypeParameters<sub>opt</sub>* `=` *Type* `;`
|
||||
|
||||
## Expressions { #grammar-expressions }
|
||||
|
||||
  *PropertyDefinition:* *( Modified )*
|
||||
   *IdentifierReference*
|
||||
   *CoverInitializedName*
|
||||
   *PropertyName* `:` *AssignmentExpression*
|
||||
   *PropertyName* *CallSignature* `{` *FunctionBody* `}`
|
||||
   *GetAccessor*
|
||||
   *SetAccessor*
|
||||
|
||||
  *GetAccessor:*
|
||||
   `get` *PropertyName* `(` `)` *TypeAnnotation<sub>opt</sub>* `{` *FunctionBody* `}`
|
||||
|
||||
  *SetAccessor:*
|
||||
   `set` *PropertyName* `(` *BindingIdentifierOrPattern* *TypeAnnotation<sub>opt</sub>* `)` `{` *FunctionBody* `}`
|
||||
|
||||
  *FunctionExpression:* *( Modified )*
|
||||
   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}`
|
||||
|
||||
  *ArrowFormalParameters:* *( Modified )*
|
||||
   *CallSignature*
|
||||
|
||||
  *Arguments:* *( Modified )*
|
||||
   *TypeArguments<sub>opt</sub>* `(` *ArgumentList<sub>opt</sub>* `)`
|
||||
|
||||
  *UnaryExpression:* *( Modified )*
|
||||
   …
|
||||
   `<` *Type* `>` *UnaryExpression*
|
||||
|
||||
## Statements { #grammar-statements }
|
||||
|
||||
  *Declaration:* *( Modified )*
|
||||
   …
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
|
||||
  *VariableDeclaration:* *( Modified )*
|
||||
   *SimpleVariableDeclaration*
|
||||
   *DestructuringVariableDeclaration*
|
||||
|
||||
  *SimpleVariableDeclaration:*
|
||||
   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>*
|
||||
|
||||
  *DestructuringVariableDeclaration:*
|
||||
   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer*
|
||||
|
||||
  *LexicalBinding:* *( Modified )*
|
||||
   *SimpleLexicalBinding*
|
||||
   *DestructuringLexicalBinding*
|
||||
|
||||
  *SimpleLexicalBinding:*
|
||||
   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>*
|
||||
|
||||
  *DestructuringLexicalBinding:*
|
||||
   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>*
|
||||
|
||||
## Functions { #grammar-functions }
|
||||
|
||||
  *FunctionDeclaration:* *( Modified )*
|
||||
   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `{` *FunctionBody* `}`
|
||||
   `function` *BindingIdentifier<sub>opt</sub>* *CallSignature* `;`
|
||||
|
||||
## Interfaces { #grammar-interfaces }
|
||||
|
||||
  *InterfaceDeclaration:*
|
||||
   `interface` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *InterfaceExtendsClause<sub>opt</sub>* *ObjectType*
|
||||
|
||||
  *InterfaceExtendsClause:*
|
||||
   `extends` *ClassOrInterfaceTypeList*
|
||||
|
||||
  *ClassOrInterfaceTypeList:*
|
||||
   *ClassOrInterfaceType*
|
||||
   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType*
|
||||
|
||||
  *ClassOrInterfaceType:*
|
||||
   *TypeReference*
|
||||
|
||||
## Classes { #grammar-classes }
|
||||
|
||||
  *ClassDeclaration:* *( Modified )*
|
||||
   `class` *BindingIdentifier<sub>opt</sub>* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *ClassBody* `}`
|
||||
|
||||
  *ClassHeritage:* *( Modified )*
|
||||
   *ClassExtendsClause<sub>opt</sub>* *ImplementsClause<sub>opt</sub>*
|
||||
|
||||
  *ClassExtendsClause:*
|
||||
   `extends`  *ClassType*
|
||||
|
||||
  *ClassType:*
|
||||
   *TypeReference*
|
||||
|
||||
  *ImplementsClause:*
|
||||
   `implements` *ClassOrInterfaceTypeList*
|
||||
|
||||
  *ClassElement:* *( Modified )*
|
||||
   *ConstructorDeclaration*
|
||||
   *PropertyMemberDeclaration*
|
||||
   *IndexMemberDeclaration*
|
||||
|
||||
  *ConstructorDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `{` *FunctionBody* `}`
|
||||
   *AccessibilityModifier<sub>opt</sub>* `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;`
|
||||
|
||||
  *PropertyMemberDeclaration:*
|
||||
   *MemberVariableDeclaration*
|
||||
   *MemberFunctionDeclaration*
|
||||
   *MemberAccessorDeclaration*
|
||||
|
||||
  *MemberVariableDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>* `;`
|
||||
|
||||
  *MemberFunctionDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `{` *FunctionBody* `}`
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;`
|
||||
|
||||
  *MemberAccessorDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *GetAccessor*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *SetAccessor*
|
||||
|
||||
  *IndexMemberDeclaration:*
|
||||
   *IndexSignature* `;`
|
||||
|
||||
## Enums { #grammar-enums }
|
||||
|
||||
  *EnumDeclaration:*
|
||||
   `const`*<sub>opt</sub>* `enum` *BindingIdentifier* `{` *EnumBody<sub>opt</sub>* `}`
|
||||
|
||||
  *EnumBody:*
|
||||
   *EnumMemberList* `,`*<sub>opt</sub>*
|
||||
|
||||
  *EnumMemberList:*
|
||||
   *EnumMember*
|
||||
   *EnumMemberList* `,` *EnumMember*
|
||||
|
||||
  *EnumMember:*
|
||||
   *PropertyName*
|
||||
   *PropertyName* = *EnumValue*
|
||||
|
||||
  *EnumValue:*
|
||||
   *AssignmentExpression*
|
||||
|
||||
## Namespaces { #grammar-namespaces }
|
||||
|
||||
  *NamespaceDeclaration:*
|
||||
   `namespace` *IdentifierPath* `{` *NamespaceBody* `}`
|
||||
|
||||
  *IdentifierPath:*
|
||||
   *BindingIdentifier*
|
||||
   *IdentifierPath* `.` *BindingIdentifier*
|
||||
|
||||
  *NamespaceBody:*
|
||||
   *NamespaceElements<sub>opt</sub>*
|
||||
|
||||
  *NamespaceElements:*
|
||||
   *NamespaceElement*
|
||||
   *NamespaceElements* *NamespaceElement*
|
||||
|
||||
  *NamespaceElement:*
|
||||
   *Statement*
|
||||
   *LexicalDeclaration*
|
||||
   *FunctionDeclaration*
|
||||
   *GeneratorDeclaration*
|
||||
   *ClassDeclaration*
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
   *NamespaceDeclaration
|
||||
   AmbientDeclaration
|
||||
   ImportAliasDeclaration
|
||||
   ExportNamespaceElement*
|
||||
|
||||
  *ExportNamespaceElement:*
|
||||
   `export` *VariableStatement*
|
||||
   `export` *LexicalDeclaration*
|
||||
   `export` *FunctionDeclaration*
|
||||
   `export` *GeneratorDeclaration*
|
||||
   `export` *ClassDeclaration*
|
||||
   `export` *InterfaceDeclaration*
|
||||
   `export` *TypeAliasDeclaration*
|
||||
   `export` *EnumDeclaration*
|
||||
   `export` *NamespaceDeclaration*
|
||||
   `export` *AmbientDeclaration*
|
||||
   `export` *ImportAliasDeclaration*
|
||||
|
||||
  *ImportAliasDeclaration:*
|
||||
   `import` *BindingIdentifier* `=` *EntityName* `;`
|
||||
|
||||
  *EntityName:*
|
||||
   *NamespaceName*
|
||||
   *NamespaceName* `.` *IdentifierReference*
|
||||
|
||||
## Scripts and Modules { #grammar-scripts-and-modules }
|
||||
|
||||
  *SourceFile:*
|
||||
   *ImplementationSourceFile*
|
||||
   *DeclarationSourceFile*
|
||||
|
||||
  *ImplementationSourceFile:*
|
||||
   *ImplementationScript*
|
||||
   *ImplementationModule*
|
||||
|
||||
  *DeclarationSourceFile:*
|
||||
   *DeclarationScript*
|
||||
   *DeclarationModule*
|
||||
|
||||
  *ImplementationScript:*
|
||||
   *ImplementationScriptElements<sub>opt</sub>*
|
||||
|
||||
  *ImplementationScriptElements:*
|
||||
   *ImplementationScriptElement*
|
||||
   *ImplementationScriptElements* *ImplementationScriptElement*
|
||||
|
||||
  *ImplementationScriptElement:*
|
||||
   *ImplementationElement*
|
||||
   *AmbientModuleDeclaration*
|
||||
|
||||
  *ImplementationElement:*
|
||||
   *Statement*
|
||||
   *LexicalDeclaration*
|
||||
   *FunctionDeclaration*
|
||||
   *GeneratorDeclaration*
|
||||
   *ClassDeclaration*
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
   *NamespaceDeclaration*
|
||||
   *AmbientDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
|
||||
  *DeclarationScript:*
|
||||
   *DeclarationScriptElements<sub>opt</sub>*
|
||||
|
||||
  *DeclarationScriptElements:*
|
||||
   *DeclarationScriptElement*
|
||||
   *DeclarationScriptElements* *DeclarationScriptElement*
|
||||
|
||||
  *DeclarationScriptElement:*
|
||||
   *DeclarationElement*
|
||||
   *AmbientModuleDeclaration*
|
||||
|
||||
  *DeclarationElement:*
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *NamespaceDeclaration*
|
||||
   *AmbientDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
|
||||
  *ImplementationModule:*
|
||||
   *ImplementationModuleElements<sub>opt</sub>*
|
||||
|
||||
  *ImplementationModuleElements:*
|
||||
   *ImplementationModuleElement*
|
||||
   *ImplementationModuleElements* *ImplementationModuleElement*
|
||||
|
||||
  *ImplementationModuleElement:*
|
||||
   *ImplementationElement*
|
||||
   *ImportDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
   *ImportRequireDeclaration*
|
||||
   *ExportImplementationElement*
|
||||
   *ExportDefaultImplementationElement*
|
||||
   *ExportListDeclaration*
|
||||
   *ExportAssignment*
|
||||
|
||||
  *DeclarationModule:*
|
||||
   *DeclarationModuleElements<sub>opt</sub>*
|
||||
|
||||
  *DeclarationModuleElements:*
|
||||
   *DeclarationModuleElement*
|
||||
   *DeclarationModuleElements* *DeclarationModuleElement*
|
||||
|
||||
  *DeclarationModuleElement:*
|
||||
   *DeclarationElement*
|
||||
   *ImportDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
   *ExportDeclarationElement*
|
||||
   *ExportDefaultDeclarationElement*
|
||||
   *ExportListDeclaration*
|
||||
   *ExportAssignment*
|
||||
|
||||
  *ImportRequireDeclaration:*
|
||||
   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;`
|
||||
|
||||
  *ExportImplementationElement:*
|
||||
   `export` *VariableStatement*
|
||||
   `export` *LexicalDeclaration*
|
||||
   `export` *FunctionDeclaration*
|
||||
   `export` *GeneratorDeclaration*
|
||||
   `export` *ClassDeclaration*
|
||||
   `export` *InterfaceDeclaration*
|
||||
   `export` *TypeAliasDeclaration*
|
||||
   `export` *EnumDeclaration*
|
||||
   `export` *NamespaceDeclaration*
|
||||
   `export` *AmbientDeclaration*
|
||||
   `export` *ImportAliasDeclaration*
|
||||
|
||||
  *ExportDeclarationElement:*
|
||||
   `export` *InterfaceDeclaration*
|
||||
   `export` *TypeAliasDeclaration*
|
||||
   `export` *AmbientDeclaration*
|
||||
   `export` *ImportAliasDeclaration*
|
||||
|
||||
  *ExportDefaultImplementationElement:*
|
||||
   `export` `default` *FunctionDeclaration*
|
||||
   `export` `default` *GeneratorDeclaration*
|
||||
   `export` `default` *ClassDeclaration*
|
||||
   `export` `default` *AssignmentExpression* `;`
|
||||
|
||||
  *ExportDefaultDeclarationElement:*
|
||||
   `export` `default` *AmbientFunctionDeclaration*
|
||||
   `export` `default` *AmbientClassDeclaration*
|
||||
   `export` `default` *IdentifierReference* `;`
|
||||
|
||||
  *ExportListDeclaration:*
|
||||
   `export` `*` *FromClause* `;`
|
||||
   `export` *ExportClause* *FromClause* `;`
|
||||
   `export` *ExportClause* `;`
|
||||
|
||||
  *ExportAssignment:*
|
||||
   `export` `=` *IdentifierReference* `;`
|
||||
|
||||
## Ambients { #grammar-ambients }
|
||||
|
||||
  *AmbientDeclaration:*
|
||||
   `declare` *AmbientVariableDeclaration*
|
||||
   `declare` *AmbientFunctionDeclaration*
|
||||
   `declare` *AmbientClassDeclaration*
|
||||
   `declare` *AmbientEnumDeclaration*
|
||||
   `declare` *AmbientNamespaceDeclaration*
|
||||
|
||||
  *AmbientVariableDeclaration:*
|
||||
   `var` *AmbientBindingList* `;`
|
||||
   `let` *AmbientBindingList* `;`
|
||||
   `const` *AmbientBindingList* `;`
|
||||
|
||||
  *AmbientBindingList:*
|
||||
   *AmbientBinding*
|
||||
   *AmbientBindingList* `,` *AmbientBinding*
|
||||
|
||||
  *AmbientBinding:*
|
||||
   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>*
|
||||
|
||||
  *AmbientFunctionDeclaration:*
|
||||
   `function` *BindingIdentifier* *CallSignature* `;`
|
||||
|
||||
  *AmbientClassDeclaration:*
|
||||
   `class` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *ClassHeritage* `{` *AmbientClassBody* `}`
|
||||
|
||||
  *AmbientClassBody:*
|
||||
   *AmbientClassBodyElements<sub>opt</sub>*
|
||||
|
||||
  *AmbientClassBodyElements:*
|
||||
   *AmbientClassBodyElement*
|
||||
   *AmbientClassBodyElements* *AmbientClassBodyElement*
|
||||
|
||||
  *AmbientClassBodyElement:*
|
||||
   *AmbientConstructorDeclaration*
|
||||
   *AmbientPropertyMemberDeclaration*
|
||||
   *IndexSignature*
|
||||
|
||||
  *AmbientConstructorDeclaration:*
|
||||
   `constructor` `(` *ParameterList<sub>opt</sub>* `)` `;`
|
||||
|
||||
  *AmbientPropertyMemberDeclaration:*
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *TypeAnnotation<sub>opt</sub>* `;`
|
||||
   *AccessibilityModifier<sub>opt</sub>* `static`*<sub>opt</sub>* *PropertyName* *CallSignature* `;`
|
||||
|
||||
  *AmbientEnumDeclaration:*
|
||||
   *EnumDeclaration*
|
||||
|
||||
  *AmbientNamespaceDeclaration:*
|
||||
   `namespace` *IdentifierPath* `{` *AmbientNamespaceBody* `}`
|
||||
|
||||
  *AmbientNamespaceBody:*
|
||||
   *AmbientNamespaceElements<sub>opt</sub>*
|
||||
|
||||
  *AmbientNamespaceElements:*
|
||||
   *AmbientNamespaceElement*
|
||||
   *AmbientNamespaceElements* *AmbientNamespaceElement*
|
||||
|
||||
  *AmbientNamespaceElement:*
|
||||
   `export`*<sub>opt</sub>* *AmbientVariableDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientLexicalDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientFunctionDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientClassDeclaration*
|
||||
   `export`*<sub>opt</sub>* *InterfaceDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientEnumDeclaration*
|
||||
   `export`*<sub>opt</sub>* *AmbientNamespaceDeclaration*
|
||||
   `export`*<sub>opt</sub>* *ImportAliasDeclaration*
|
||||
|
||||
  *AmbientModuleDeclaration:*
|
||||
   `declare` `module` *StringLiteral* `{`  *DeclarationModule* `}`
|
||||
|
||||
176
doc/spec/Interfaces.md
Normal file
176
doc/spec/Interfaces.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# Interfaces { #interfaces }
|
||||
|
||||
Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones.
|
||||
|
||||
Interfaces have no run-time representation—they are purely a compile-time construct. 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 [#type-and-member-identity]<!--3.11.2-->).
|
||||
|
||||
Class declarations may reference interfaces in their implements clause to validate that they provide an implementation of the interfaces.
|
||||
|
||||
## Interface Declarations { #interface-declarations }
|
||||
|
||||
An interface declaration declares an ***interface type***.
|
||||
|
||||
  *InterfaceDeclaration:*
|
||||
   `interface` *BindingIdentifier* *TypeParameters<sub>opt</sub>* *InterfaceExtendsClause<sub>opt</sub>* *ObjectType*
|
||||
|
||||
  *InterfaceExtendsClause:*
|
||||
   `extends` *ClassOrInterfaceTypeList*
|
||||
|
||||
  *ClassOrInterfaceTypeList:*
|
||||
   *ClassOrInterfaceType*
|
||||
   *ClassOrInterfaceTypeList* `,` *ClassOrInterfaceType*
|
||||
|
||||
  *ClassOrInterfaceType:*
|
||||
   *TypeReference*
|
||||
|
||||
An *InterfaceDeclaration* introduces a named type (section [#named-types]<!--3.7-->) in the containing declaration space. The *BindingIdentifier* of an interface declaration may not be one of the predefined type names (section [#predefined-types]<!--3.8.1-->).
|
||||
|
||||
An interface may optionally have type parameters (section [#type-parameter-lists]<!--3.6.1-->) that serve as placeholders for actual types to be provided when the interface is referenced in type references. An interface with type parameters is called a ***generic interface***. The type parameters of a generic interface declaration are in scope in the entire declaration and may be referenced in the *InterfaceExtendsClause* and *ObjectType* body.
|
||||
|
||||
An interface can inherit from zero or more ***base types*** which are specified in the *InterfaceExtendsClause*. The base types must be type references to class or interface types.
|
||||
|
||||
An interface has the members specified in the *ObjectType* of its declaration and furthermore inherits all base type members that aren't hidden by declarations in the interface:
|
||||
|
||||
* A property declaration hides a public base type property with the same name.
|
||||
* A string index signature declaration hides a base type string index signature.
|
||||
* A numeric index signature declaration hides a base type numeric index signature.
|
||||
|
||||
The following constraints must be satisfied by an interface declaration or otherwise a compile-time error occurs:
|
||||
|
||||
* An interface declaration may not, directly or indirectly, specify a base type that originates in the same declaration. In other words an interface cannot, directly or indirectly, be a base type of itself, regardless of type arguments.
|
||||
* An interface cannot declare a property with the same name as an inherited private or protected property.
|
||||
* Inherited properties with the same name must be identical (section [#type-and-member-identity]<!--3.11.2-->).
|
||||
* All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [#index-signatures]<!--3.9.4-->.
|
||||
* The this-type (section [#this-types]<!--3.6.3-->) of the declared interface must be assignable (section [#assignment-compatibility]<!--3.11.4-->) to each of the base type references.
|
||||
|
||||
An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member.
|
||||
|
||||
Below is an example of two interfaces that contain properties with the same name but different types:
|
||||
|
||||
```TypeScript
|
||||
interface Mover {
|
||||
move(): void;
|
||||
getStatus(): { speed: number; };
|
||||
}
|
||||
|
||||
interface Shaker {
|
||||
shake(): void;
|
||||
getStatus(): { frequency: number; };
|
||||
}
|
||||
```
|
||||
|
||||
An interface that extends 'Mover' and 'Shaker' must declare a new 'getStatus' property as it would otherwise inherit two 'getStatus' properties with different types. The new 'getStatus' property must be declared such that the resulting 'MoverShaker' is a subtype of both 'Mover' and 'Shaker':
|
||||
|
||||
```TypeScript
|
||||
interface MoverShaker extends Mover, Shaker {
|
||||
getStatus(): { speed: number; frequency: number; };
|
||||
}
|
||||
```
|
||||
|
||||
Since function and constructor types are just object types containing call and construct signatures, interfaces can be used to declare named function and constructor types. For example:
|
||||
|
||||
```TypeScript
|
||||
interface StringComparer { (a: string, b: string): number; }
|
||||
```
|
||||
|
||||
This declares type 'StringComparer' to be a function type taking two strings and returning a number.
|
||||
|
||||
## Declaration Merging { #declaration-merging }
|
||||
|
||||
Interfaces are "open-ended" and interface declarations with the same qualified name relative to a common root (as defined in section [#declarations]<!--2.3-->) contribute to a single interface.
|
||||
|
||||
When a generic interface has multiple declarations, all declarations must have identical type parameter lists, i.e. identical type parameter names with identical constraints in identical order.
|
||||
|
||||
In an interface with multiple declarations, the `extends` clauses are merged into a single set of base types and the bodies of the interface declarations are merged into a single object type. Declaration merging produces a declaration order that corresponds to *prepending* the members of each interface declaration, in the order the members are written, to the combined list of members in the order of the interface declarations. Thus, members declared in the last interface declaration will appear first in the declaration order of the merged type.
|
||||
|
||||
For example, a sequence of declarations in this order:
|
||||
|
||||
```TypeScript
|
||||
interface Document {
|
||||
createElement(tagName: any): Element;
|
||||
}
|
||||
|
||||
interface Document {
|
||||
createElement(tagName: string): HTMLElement;
|
||||
}
|
||||
|
||||
interface Document {
|
||||
createElement(tagName: "div"): HTMLDivElement;
|
||||
createElement(tagName: "span"): HTMLSpanElement;
|
||||
createElement(tagName: "canvas"): HTMLCanvasElement;
|
||||
}
|
||||
```
|
||||
|
||||
is equivalent to the following single declaration:
|
||||
|
||||
```TypeScript
|
||||
interface Document {
|
||||
createElement(tagName: "div"): HTMLDivElement;
|
||||
createElement(tagName: "span"): HTMLSpanElement;
|
||||
createElement(tagName: "canvas"): HTMLCanvasElement;
|
||||
createElement(tagName: string): HTMLElement;
|
||||
createElement(tagName: any): Element;
|
||||
}
|
||||
```
|
||||
|
||||
Note that the members of the last interface declaration appear first in the merged declaration. Also note that the relative order of members declared in the same interface body is preserved.
|
||||
|
||||
*TODO: Document [class and interface declaration merging](https://github.com/Microsoft/TypeScript/pull/3333)*.
|
||||
|
||||
## Interfaces Extending Classes { #interfaces-extending-classes }
|
||||
|
||||
When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example:
|
||||
|
||||
```TypeScript
|
||||
class Control {
|
||||
private state: any;
|
||||
}
|
||||
|
||||
interface SelectableControl extends Control {
|
||||
select(): void;
|
||||
}
|
||||
|
||||
class Button extends Control {
|
||||
select() { }
|
||||
}
|
||||
|
||||
class TextBox extends Control {
|
||||
select() { }
|
||||
}
|
||||
|
||||
class Image extends Control {
|
||||
}
|
||||
|
||||
class Location {
|
||||
select() { }
|
||||
}
|
||||
```
|
||||
|
||||
In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [#type-relationships]<!--3.11-->).
|
||||
|
||||
Within the 'Control' class it is possible to access the 'state' private member through an instance of 'SelectableControl'. Effectively, a 'SelectableControl' acts like a 'Control' that is known to have a 'select' method. The 'Button' and 'TextBox' classes are subtypes of 'SelectableControl' (because they both inherit from 'Control' and have a 'select' method), but the 'Image' and 'Location' classes are not.
|
||||
|
||||
## Dynamic Type Checks { #dynamic-type-checks }
|
||||
|
||||
TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface. Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example, given the declarations in section [#interface-declarations]<!--7.1-->, the following is a dynamic check for the 'MoverShaker' interface:
|
||||
|
||||
```TypeScript
|
||||
var obj: any = getSomeObject();
|
||||
if (obj && obj.move && obj.shake && obj.getStatus) {
|
||||
var moverShaker = <MoverShaker> obj;
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
If such a check is used often it can be abstracted into a function:
|
||||
|
||||
```TypeScript
|
||||
function asMoverShaker(obj: any): MoverShaker {
|
||||
return obj && obj.move && obj.shake && obj.getStatus ? obj : null;
|
||||
}
|
||||
```
|
||||
|
||||
<br/>
|
||||
|
||||
542
doc/spec/Intro.md
Normal file
542
doc/spec/Intro.md
Normal file
@@ -0,0 +1,542 @@
|
||||
# Introduction { #introduction }
|
||||
|
||||
JavaScript applications such as web 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. 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 2015 (ES2015) 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 all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code.
|
||||
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
var i = 0;
|
||||
```
|
||||
|
||||
TypeScript will infer from the following function definition that the function f has return type string.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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:
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
## Ambient Declarations { #ambient-declarations }
|
||||
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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:
|
||||
|
||||
```TypeScript
|
||||
declare var $;
|
||||
```
|
||||
|
||||
Section [#object-types]<!--1.3--> provides a more extensive example of how a programmer can add type information for jQuery and other libraries.
|
||||
|
||||
## Function Types { #function-types }
|
||||
|
||||
Function expressions are a powerful feature of JavaScript. 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.
|
||||
|
||||
```TypeScript
|
||||
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
|
||||
|
||||
```TypeScript
|
||||
(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 [#call-signatures]<!--3.9.2--> provides additional information about function types.
|
||||
|
||||
## Object Types { #object-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.
|
||||
|
||||
```TypeScript
|
||||
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).
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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
|
||||
|
||||
```TypeScript
|
||||
(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 one or more call signatures. 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.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
(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 [#object-types]<!--3.3--> provides additional information about object types.
|
||||
|
||||
## Structural Subtyping { #structural-subtyping }
|
||||
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function getX(p: Point) {
|
||||
return p.x;
|
||||
}
|
||||
|
||||
class CPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
constructor(x: number, y: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
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 [#type-relationships]<!--3.11--> for more information about type comparisons.
|
||||
|
||||
## Contextual Typing { #contextual-typing }
|
||||
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
$.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 [#contextually-typed-expressions]<!--4.23--> provides additional information about contextually typed expressions.
|
||||
|
||||
## Classes { #classes }
|
||||
|
||||
JavaScript practice has two very 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. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 2015 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.)
|
||||
|
||||
This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or namespace 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.
|
||||
|
||||
```TypeScript
|
||||
class BankAccount {
|
||||
balance = 0;
|
||||
deposit(credit: number) {
|
||||
this.balance += credit;
|
||||
return this.balance;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This class generates the following JavaScript code.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
```TypeScript
|
||||
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 accessibility for class members, but a programmer can also specify private or protected accessibility for a class member. Accessibility 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.* *
|
||||
|
||||
```TypeScript
|
||||
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 'BankAccount'.
|
||||
|
||||
TypeScript classes may also specify static members. Static class members become properties of the class constructor.
|
||||
|
||||
Section [#classes]<!--8--> provides additional information about classes.
|
||||
|
||||
## Enum Types { #enum-types }
|
||||
|
||||
TypeScript enables programmers to summarize a set of numeric constants as an *enum type*. The example below creates an enum type to represent operators in a calculator application.
|
||||
|
||||
```TypeScript
|
||||
const enum Operator {
|
||||
ADD,
|
||||
DIV,
|
||||
MUL,
|
||||
SUB
|
||||
}
|
||||
|
||||
function compute(op: Operator, a: number, b: number) {
|
||||
console.log("the operator is" + Operator[op]);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the compute function logs the operator 'op' using a feature of enum types: reverse mapping from the enum value ('op') to the string corresponding to that value. For example, the declaration of 'Operator' automatically assigns integers, starting from zero, to the listed enum members. Section [#enums]<!--9--> describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member.
|
||||
|
||||
When enums are declared with the `const` modifier, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member's assigned value (annotated with a comment). This improves performance on many JavaScript engines.
|
||||
|
||||
For example, the 'compute' function could contain a switch statement like the following.
|
||||
|
||||
```TypeScript
|
||||
switch (op) {
|
||||
case Operator.ADD:
|
||||
// execute add
|
||||
break;
|
||||
case Operator.DIV:
|
||||
// execute div
|
||||
break;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
For this switch statement, the compiler will generate the following code.
|
||||
|
||||
```TypeScript
|
||||
switch (op) {
|
||||
case 0 /* Operator.ADD */:
|
||||
// execute add
|
||||
break;
|
||||
case 1 /* Operator.DIV */:
|
||||
// execute div
|
||||
break;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript implementations can use these explicit constants to generate efficient code for this switch statement, for example by building a jump table indexed by case value.
|
||||
|
||||
## Overloading on String Parameters { #overloading-on-string-parameters }
|
||||
|
||||
An important goal of TypeScript is to provide accurate and straightforward types for existing JavaScript programming patterns. To that end, TypeScript includes generic types, discussed in the next section, and *overloading on string parameters*, the topic of this section.
|
||||
|
||||
JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screen shot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method.
|
||||
|
||||
  
|
||||
|
||||
The following code fragment uses this feature. Because the 'span' variable is inferred to have the type 'HTMLSpanElement', the code can reference without static error the 'isMultiline' property of 'span'.
|
||||
|
||||
```TypeScript
|
||||
var span = document.createElement("span");
|
||||
span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property
|
||||
```
|
||||
|
||||
In the following screen shot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property.
|
||||
|
||||
  
|
||||
|
||||
Section [#specialized-signatures]<!--3.9.2.4--> provides details on how to use string literals in function signatures.
|
||||
|
||||
## Generic Types and Functions { #generic-types-and-functions }
|
||||
|
||||
Like overloading on string parameters, *generic types* make it easier for TypeScript to accurately capture the behavior of JavaScript libraries. Because they enable type information to flow from client code, through library code, and back into client code, generic types may do more than any other TypeScript feature to support detailed API descriptions.
|
||||
|
||||
To illustrate this, let's take a look at part of the TypeScript interface for the built-in JavaScript array type. You can find this interface in the 'lib.d.ts' file that accompanies a TypeScript distribution.
|
||||
|
||||
```TypeScript
|
||||
interface Array<T> {
|
||||
reverse(): T[];
|
||||
sort(compareFn?: (a: T, b: T) => number): T[];
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Interface definitions, like the one above, can have one or more *type parameters*. In this case the 'Array' interface has a single parameter, 'T', that defines the element type for the array. The 'reverse' method returns an array with the same element type. The sort method takes an optional parameter, 'compareFn', whose type is a function that takes two parameters of type 'T' and returns a number. Finally, sort returns an array with element type 'T'.
|
||||
|
||||
Functions can also have generic parameters. For example, the array interface contains a 'map' method, defined as follows:
|
||||
|
||||
```TypeScript
|
||||
map<U>(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
|
||||
```
|
||||
|
||||
The map method, invoked on an array 'a' with element type 'T', will apply function 'func' to each element of 'a', returning a value of type 'U'.
|
||||
|
||||
The TypeScript compiler can often infer generic method parameters, making it unnecessary for the programmer to explicitly provide them. In the following example, the compiler infers that parameter 'U' of the map method has type 'string', because the function passed to map returns a string.
|
||||
|
||||
```TypeScript
|
||||
function numberToString(a: number[]) {
|
||||
var stringArray = a.map(v => v.toString());
|
||||
return stringArray;
|
||||
}
|
||||
```
|
||||
|
||||
The compiler infers in this example that the 'numberToString' function returns an array of strings.
|
||||
|
||||
In TypeScript, classes can also have type parameters. The following code declares a class that implements a linked list of items of type 'T'. This code illustrates how programmers can *constrain* type parameters to extend a specific type. In this case, the items on the list must extend the type 'NamedItem'. This enables the programmer to implement the 'log' function, which logs the name of the item.
|
||||
|
||||
```TypeScript
|
||||
interface NamedItem {
|
||||
name: string;
|
||||
}
|
||||
|
||||
class List<T extends NamedItem> {
|
||||
next: List<T> = null;
|
||||
|
||||
constructor(public item: T) {
|
||||
}
|
||||
|
||||
insertAfter(item: T) {
|
||||
var temp = this.next;
|
||||
this.next = new List(item);
|
||||
this.next.next = temp;
|
||||
}
|
||||
|
||||
log() {
|
||||
console.log(this.item.name);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Section [#named-types]<!--3.7--> provides further information about generic types.
|
||||
|
||||
## Namespaces { #namespaces }
|
||||
|
||||
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 and protected 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 and protected members.
|
||||
|
||||
In JavaScript, a very common 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. The module pattern 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.
|
||||
|
||||
```TypeScript
|
||||
(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 namespaces provide a mechanism for succinctly expressing the module pattern. In TypeScript, programmers can combine the module pattern with the class pattern by nesting namespaces and classes within an outer namespace.
|
||||
|
||||
The following example shows the definition and use of a simple namespace.
|
||||
|
||||
```TypeScript
|
||||
namespace 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 namespace, but function 'f' is exported from the namespace and accessible to code outside of the namespace. If we were to describe the effect of namespace 'M' in terms of interfaces and variables, we would write
|
||||
|
||||
```TypeScript
|
||||
interface M {
|
||||
f(): string;
|
||||
}
|
||||
|
||||
var M: M;
|
||||
```
|
||||
|
||||
The interface 'M' summarizes the externally visible behavior of namespace '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 [#declarations]<!--2.3--> for more details).
|
||||
|
||||
The TypeScript compiler emits the following JavaScript code for the namespace:
|
||||
|
||||
```TypeScript
|
||||
var M;
|
||||
(function(M) {
|
||||
var s = "hello";
|
||||
function f() {
|
||||
return s;
|
||||
}
|
||||
M.f = f;
|
||||
})(M || (M = {}));
|
||||
```
|
||||
|
||||
In this case, the compiler assumes that the namespace object resides in global variable 'M', which may or may not have been initialized to the desired namespace object.
|
||||
|
||||
## Modules { #modules }
|
||||
|
||||
TypeScript also supports ECMAScript 2015 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 2015 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD).
|
||||
|
||||
<br/>
|
||||
319
doc/spec/Namespaces.md
Normal file
319
doc/spec/Namespaces.md
Normal file
@@ -0,0 +1,319 @@
|
||||
# Namespaces { #namespaces }
|
||||
|
||||
Namespaces provide a mechanism for organizing code and declarations in hierarchies of named containers. Namespaces have named members that each denote a value, a type, or a namespace, or some combination thereof, and those members may be local or exported. The body of a namespace corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation. Namespaces can be thought of as a formalization of the [immediately-invoked function expression](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) (IIFE) pattern.
|
||||
|
||||
## Namespace Declarations { #namespace-declarations }
|
||||
|
||||
A namespace declaration introduces a name with a namespace meaning and, in the case of an instantiated namespace, a value meaning in the containing declaration space.
|
||||
|
||||
  *NamespaceDeclaration:*
|
||||
   `namespace` *IdentifierPath* `{` *NamespaceBody* `}`
|
||||
|
||||
  *IdentifierPath:*
|
||||
   *BindingIdentifier*
|
||||
   *IdentifierPath* `.` *BindingIdentifier*
|
||||
|
||||
Namespaces are declared using the `namespace` keyword, but for backward compatibility of earlier versions of TypeScript a `module` keyword can also be used.
|
||||
|
||||
Namespaces are either ***instantiated*** or ***non-instantiated***. A non-instantiated namespace is a namespace containing only interface types, type aliases, and other non-instantiated namespace. An instantiated namespace is a namespace that doesn't meet this definition. In intuitive terms, an instantiated namespace is one for which a namespace instance is created, whereas a non-instantiated namespace is one for which no code is generated.
|
||||
|
||||
When a namespace identifier is referenced as a *NamespaceName* (section [#type-references]<!--3.8.2-->) it denotes a container of namespace and type names, and when a namespace identifier is referenced as a *PrimaryExpression* (section [#identifiers]<!--4.3-->) it denotes the singleton namespace instance. For example:
|
||||
|
||||
```TypeScript
|
||||
namespace M {
|
||||
export interface P { x: number; y: number; }
|
||||
export var a = 1;
|
||||
}
|
||||
|
||||
var p: M.P; // M used as NamespaceName
|
||||
var m = M; // M used as PrimaryExpression
|
||||
var x1 = M.a; // M used as PrimaryExpression
|
||||
var x2 = m.a; // Same as M.a
|
||||
var q: m.P; // Error
|
||||
```
|
||||
|
||||
Above, when 'M' is used as a *PrimaryExpression* it denotes an object instance with a single member 'a' and when 'M' is used as a *NamespaceName* it denotes a container with a single type member 'P'. The final line in the example is an error because 'm' is a variable which cannot be referenced in a type name.
|
||||
|
||||
If the declaration of 'M' above had excluded the exported variable 'a', 'M' would be a non-instantiated namespace and it would be an error to reference 'M' as a *PrimaryExpression*.
|
||||
|
||||
A namespace declaration that specifies an *IdentifierPath* with more than one identifier is equivalent to a series of nested single-identifier namespace declarations where all but the outermost are automatically exported. For example:
|
||||
|
||||
```TypeScript
|
||||
namespace A.B.C {
|
||||
export var x = 1;
|
||||
}
|
||||
```
|
||||
|
||||
corresponds to
|
||||
|
||||
```TypeScript
|
||||
namespace A {
|
||||
export namespace B {
|
||||
export namespace C {
|
||||
export var x = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The hierarchy formed by namespace and named type names partially mirrors that formed by namespace instances and members. The example
|
||||
|
||||
```TypeScript
|
||||
namespace A {
|
||||
export namespace 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
|
||||
|
||||
```TypeScript
|
||||
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.
|
||||
|
||||
## Namespace Body { #namespace-body }
|
||||
|
||||
The body of a namespace corresponds to a function that is executed once to initialize the namespace instance.
|
||||
|
||||
  *NamespaceBody:*
|
||||
   *NamespaceElements<sub>opt</sub>*
|
||||
|
||||
  *NamespaceElements:*
|
||||
   *NamespaceElement*
|
||||
   *NamespaceElements* *NamespaceElement*
|
||||
|
||||
  *NamespaceElement:*
|
||||
   *Statement*
|
||||
   *LexicalDeclaration*
|
||||
   *FunctionDeclaration*
|
||||
   *GeneratorDeclaration*
|
||||
   *ClassDeclaration*
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
   *NamespaceDeclaration
|
||||
   AmbientDeclaration
|
||||
   ImportAliasDeclaration
|
||||
   ExportNamespaceElement*
|
||||
|
||||
  *ExportNamespaceElement:*
|
||||
   `export` *VariableStatement*
|
||||
   `export` *LexicalDeclaration*
|
||||
   `export` *FunctionDeclaration*
|
||||
   `export` *GeneratorDeclaration*
|
||||
   `export` *ClassDeclaration*
|
||||
   `export` *InterfaceDeclaration*
|
||||
   `export` *TypeAliasDeclaration*
|
||||
   `export` *EnumDeclaration*
|
||||
   `export` *NamespaceDeclaration*
|
||||
   `export` *AmbientDeclaration*
|
||||
   `export` *ImportAliasDeclaration*
|
||||
|
||||
## Import Alias Declarations { #import-alias-declarations }
|
||||
|
||||
Import alias declarations are used to create local aliases for entities in other namespaces.
|
||||
|
||||
  *ImportAliasDeclaration:*
|
||||
   `import` *BindingIdentifier* `=` *EntityName* `;`
|
||||
|
||||
  *EntityName:*
|
||||
   *NamespaceName*
|
||||
   *NamespaceName* `.` *IdentifierReference*
|
||||
|
||||
An *EntityName* consisting of a single identifier is resolved as a *NamespaceName* and is thus required to reference a namespace. The resulting local alias references the given namespace and is itself classified as a namespace.
|
||||
|
||||
An *EntityName* consisting of more than one identifier is resolved as a *NamespaceName* followed by an identifier that names an exported entity in the given namespace. The resulting local alias has all the meanings of the referenced entity. (As many as three distinct meanings are possible for an entity name—value, type, and namespace.) In effect, it is as if the imported entity was declared locally with the local alias name.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
namespace A {
|
||||
export interface X { s: string }
|
||||
export var X: X;
|
||||
}
|
||||
|
||||
namespace B {
|
||||
interface A { n: number }
|
||||
import Y = A; // Alias for namespace A
|
||||
import Z = A.X; // Alias for type and value A.X
|
||||
var v: Z = Z;
|
||||
}
|
||||
```
|
||||
|
||||
within 'B', 'Y' is an alias only for namespace 'A' and not the local interface 'A', whereas 'Z' is an alias for all exported meanings of 'A.X', thus denoting both an interface type and a variable.
|
||||
|
||||
If the *NamespaceName* portion of an *EntityName* references an instantiated namespace, the *NamespaceName* is required to reference the namespace instance when evaluated as an expression. In the example
|
||||
|
||||
```TypeScript
|
||||
namespace A {
|
||||
export interface X { s: string }
|
||||
}
|
||||
|
||||
namespace B {
|
||||
var A = 1;
|
||||
import Y = A;
|
||||
}
|
||||
```
|
||||
|
||||
'Y' is a local alias for the non-instantiated namespace 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated namespace, for example by including a variable declaration in 'A', the import statement in 'B' above would be an error because the expression 'A' doesn't reference the namespace instance of namespace 'A'.
|
||||
|
||||
When an import statement includes an export modifier, all meanings of the local alias are exported.
|
||||
|
||||
## Export Declarations { #export-declarations }
|
||||
|
||||
An export declaration declares an externally accessible namespace member. An export declaration is simply a regular declaration prefixed with the keyword `export`.
|
||||
|
||||
The members of a namespace's export declaration space (section [#declarations]<!--2.3-->) constitute the namespace's ***export member set***. A namespace's ***instance type*** is an object type with a property for each member in the namespace's export member set that denotes a value.
|
||||
|
||||
An exported member depends on a (possibly empty) set of named types (section [#named-types]<!--3.7-->). Those named types must be at least as accessible as the exported member, or otherwise an error occurs.
|
||||
|
||||
The named types upon which a member depends are the named types occurring in the transitive closure of the ***directly depends on*** relationship defined as follows:
|
||||
|
||||
* A variable directly depends on the *Type* specified in its type annotation.
|
||||
* A function directly depends on each *Type* specified in a parameter or return type annotation.
|
||||
* A class directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base class or implemented interface, and each *Type* specified in a constructor parameter type annotation, public member variable type annotation, public member function parameter or return type annotation, public member accessor parameter or return type annotation, or index signature type annotation.
|
||||
* An interface directly depends on each *Type* specified as a type parameter constraint, each *TypeReference* specified as a base interface, and the *ObjectType* specified as its body.
|
||||
* A namespace directly depends on its exported members.
|
||||
* A *Type* or *ObjectType* directly depends on every *TypeReference* that occurs within the type at any level of nesting.
|
||||
* A *TypeReference* directly depends on the type it references and on each *Type* specified as a type argument.
|
||||
|
||||
A named type *T* having a root namespace *R* (section [#declarations]<!--2.3-->) is said to be ***at least as accessible as*** a member *M* if
|
||||
|
||||
* *R* is the global namespace or a module, or
|
||||
* *R* is a namespace in the parent namespace chain of *M*.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
interface A { x: string; }
|
||||
|
||||
namespace M {
|
||||
export interface B { x: A; }
|
||||
export interface C { x: B; }
|
||||
export function foo(c: C) { … }
|
||||
}
|
||||
```
|
||||
|
||||
the 'foo' function depends upon the named types 'A', 'B', and 'C'. In order to export 'foo' it is necessary to also export 'B' and 'C' as they otherwise would not be at least as accessible as 'foo'. The 'A' interface is already at least as accessible as 'foo' because I t is declared in a parent namespace of foo's namespace.
|
||||
|
||||
## Declaration Merging { #declaration-merging }
|
||||
|
||||
Namespaces are "open-ended" and namespace declarations with the same qualified name relative to a common root (as defined in section [#declarations]<!--2.3-->) contribute to a single namespace. For example, the following two declarations of a namespace 'outer' might be located in separate source files.
|
||||
|
||||
File a.ts:
|
||||
|
||||
```TypeScript
|
||||
namespace outer {
|
||||
var local = 1; // Non-exported local variable
|
||||
export var a = local; // outer.a
|
||||
export namespace inner {
|
||||
export var x = 10; // outer.inner.x
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
File b.ts:
|
||||
|
||||
```TypeScript
|
||||
namespace outer {
|
||||
var local = 2; // Non-exported local variable
|
||||
export var b = local; // outer.b
|
||||
export namespace inner {
|
||||
export var y = 20; // outer.inner.y
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Assuming the two source files are part of the same program, the two declarations will have the global namespace as their common root and will therefore contribute to the same namespace instance, the instance type of which will be:
|
||||
|
||||
```TypeScript
|
||||
{
|
||||
a: number;
|
||||
b: number;
|
||||
inner: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Declaration merging does not apply to local aliases created by import alias declarations. In other words, it is not possible have an import alias declaration and a namespace declaration for the same name within the same namespace body.
|
||||
|
||||
*TODO: Clarify rules for [alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*.
|
||||
|
||||
Declaration merging also extends to namespace declarations with the same qualified name relative to a common root as a function, class, or enum declaration:
|
||||
|
||||
* When merging a function and a namespace, the type of the function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the function provide the call signatures and the exported members of the namespace provide the properties of the combined type.
|
||||
* When merging a class and a namespace, the type of the constructor function object is merged with the instance type of the namespace. In effect, the overloads or implementation of the class constructor provide the construct signatures, and the static members of the class and exported members of the namespace provide the properties of the combined type. It is an error to have static class members and exported namespace members with the same name.
|
||||
* When merging an enum and a namespace, the type of the enum object is merged with the instance type of the namespace. In effect, the members of the enum and the exported members of the namespace provide the properties of the combined type. It is an error to have enum members and exported namespace members with the same name.
|
||||
|
||||
When merging a non-ambient function or class declaration and a non-ambient namespace declaration, the function or class declaration must be located prior to the namespace declaration in the same source file. This ensures that the shared object instance is created as a function object. (While it is possible to add properties to an object after its creation, it is not possible to make an object "callable" after the fact.)
|
||||
|
||||
The example
|
||||
|
||||
```TypeScript
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function point(x: number, y: number): Point {
|
||||
return { x: x, y: y };
|
||||
}
|
||||
|
||||
namespace point {
|
||||
export var origin = point(0, 0);
|
||||
export function equals(p1: Point, p2: Point) {
|
||||
return p1.x == p2.x && p1.y == p2.y;
|
||||
}
|
||||
}
|
||||
|
||||
var p1 = point(0, 0);
|
||||
var p2 = point.origin;
|
||||
var b = point.equals(p1, p2);
|
||||
```
|
||||
|
||||
declares 'point' as a function object with two properties, 'origin' and 'equals'. Note that the namespace declaration for 'point' is located after the function declaration.
|
||||
|
||||
## Code Generation { #code-generation }
|
||||
|
||||
A namespace generates JavaScript code that is equivalent to the following:
|
||||
|
||||
```TypeScript
|
||||
var <NamespaceName>;
|
||||
(function(<NamespaceName>) {
|
||||
<NamespaceStatements>
|
||||
})(<NamespaceName>||(<NamespaceName>={}));
|
||||
```
|
||||
|
||||
where *NamespaceName* is the name of the namespace and *NamespaceStatements* is the code generated for the statements in the namespace body. The *NamespaceName* function parameter may be prefixed with one or more underscore characters to ensure the name is unique within the function body. Note that the entire namespace is emitted as an anonymous function that is immediately executed. This ensures that local variables are in their own lexical environment isolated from the surrounding context. Also note that the generated function doesn't create and return a namespace instance, but rather it extends the existing instance (which may have just been created in the function call). This ensures that namespaces can extend each other.
|
||||
|
||||
An import statement generates code of the form
|
||||
|
||||
```TypeScript
|
||||
var <Alias> = <EntityName>;
|
||||
```
|
||||
|
||||
This code is emitted only if the imported entity is referenced as a *PrimaryExpression* somewhere in the body of the importing namespace. If an imported entity is referenced only as a *TypeName* or *NamespaceName*, nothing is emitted. This ensures that types declared in one namespace can be referenced through an import alias in another namespace with no run-time overhead.
|
||||
|
||||
When a variable is exported, all references to the variable in the body of the namespace are replaced with
|
||||
|
||||
```TypeScript
|
||||
<NamespaceName>.<VariableName>
|
||||
```
|
||||
|
||||
This effectively promotes the variable to be a property on the namespace instance and ensures that all references to the variable become references to the property.
|
||||
|
||||
When a function, class, enum, or namespace is exported, the code generated for the entity is followed by an assignment statement of the form
|
||||
|
||||
```TypeScript
|
||||
<NamespaceName>.<EntityName> = <EntityName>;
|
||||
```
|
||||
|
||||
This copies a reference to the entity into a property on the namespace instance.
|
||||
|
||||
<br/>
|
||||
|
||||
517
doc/spec/Scripts and Modules.md
Normal file
517
doc/spec/Scripts and Modules.md
Normal file
@@ -0,0 +1,517 @@
|
||||
# Scripts and Modules { #scripts-and-modules }
|
||||
|
||||
TypeScript implements support for ECMAScript 2015 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems.
|
||||
|
||||
## Programs and Source Files { #programs-and-source-files }
|
||||
|
||||
A TypeScript ***program*** consists of one or more source files.
|
||||
|
||||
  *SourceFile:*
|
||||
   *ImplementationSourceFile*
|
||||
   *DeclarationSourceFile*
|
||||
|
||||
  *ImplementationSourceFile:*
|
||||
   *ImplementationScript*
|
||||
   *ImplementationModule*
|
||||
|
||||
  *DeclarationSourceFile:*
|
||||
   *DeclarationScript*
|
||||
   *DeclarationModule*
|
||||
|
||||
Source files with extension '.ts' are ***implementation source files*** containing statements and declarations, and source files with extension '.d.ts' are ***declaration source files*** containing declarations only.
|
||||
|
||||
Declaration source files are a strict subset of implementation source files and are used to declare the static type information associated with existing JavaScript code in an adjunct manner. They are entirely optional but enable the TypeScript compiler and tools to provide better verification and assistance when integrating existing JavaScript code and libraries in a TypeScript application.
|
||||
|
||||
When a TypeScript program is compiled, all of the program's source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files.
|
||||
|
||||
### Source Files Dependencies { #source-files-dependencies }
|
||||
|
||||
The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and module import declarations as follows:
|
||||
|
||||
* A comment of the form /// <reference path="…"/> that occurs before the first token in a source file adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
|
||||
* A module import declaration that specifies a relative module name (section [#module-names]<!--11.3.1-->) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency.
|
||||
* A module import declaration that specifies a top-level module name (section [#module-names]<!--11.3.1-->) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency.
|
||||
|
||||
Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined.
|
||||
|
||||
## Scripts { #scripts }
|
||||
|
||||
Source files that contain no module import or export declarations are classified as ***scripts***. Scripts form the single ***global namespace*** and entities declared in scripts are in scope everywhere in a program.
|
||||
|
||||
  *ImplementationScript:*
|
||||
   *ImplementationScriptElements<sub>opt</sub>*
|
||||
|
||||
  *ImplementationScriptElements:*
|
||||
   *ImplementationScriptElement*
|
||||
   *ImplementationScriptElements* *ImplementationScriptElement*
|
||||
|
||||
  *ImplementationScriptElement:*
|
||||
   *ImplementationElement*
|
||||
   *AmbientModuleDeclaration*
|
||||
|
||||
  *ImplementationElement:*
|
||||
   *Statement*
|
||||
   *LexicalDeclaration*
|
||||
   *FunctionDeclaration*
|
||||
   *GeneratorDeclaration*
|
||||
   *ClassDeclaration*
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
   *NamespaceDeclaration*
|
||||
   *AmbientDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
|
||||
  *DeclarationScript:*
|
||||
   *DeclarationScriptElements<sub>opt</sub>*
|
||||
|
||||
  *DeclarationScriptElements:*
|
||||
   *DeclarationScriptElement*
|
||||
   *DeclarationScriptElements* *DeclarationScriptElement*
|
||||
|
||||
  *DeclarationScriptElement:*
|
||||
   *DeclarationElement*
|
||||
   *AmbientModuleDeclaration*
|
||||
|
||||
  *DeclarationElement:*
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *NamespaceDeclaration*
|
||||
   *AmbientDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
|
||||
The initialization order of the scripts that make up the global namespace ultimately depends on the order in which the generated JavaScript files are loaded at run-time (which, for example, may be controlled by <script/> tags that reference the generated JavaScript files).
|
||||
|
||||
## Modules { #modules }
|
||||
|
||||
Source files that contain at least one module import or export declaration are considered separate ***modules***. Non-exported entities declared in a module are in scope only in that module, but exported entities can be imported into other modules using import declarations.
|
||||
|
||||
  *ImplementationModule:*
|
||||
   *ImplementationModuleElements<sub>opt</sub>*
|
||||
|
||||
  *ImplementationModuleElements:*
|
||||
   *ImplementationModuleElement*
|
||||
   *ImplementationModuleElements* *ImplementationModuleElement*
|
||||
|
||||
  *ImplementationModuleElement:*
|
||||
   *ImplementationElement*
|
||||
   *ImportDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
   *ImportRequireDeclaration*
|
||||
   *ExportImplementationElement*
|
||||
   *ExportDefaultImplementationElement*
|
||||
   *ExportListDeclaration*
|
||||
   *ExportAssignment*
|
||||
|
||||
  *DeclarationModule:*
|
||||
   *DeclarationModuleElements<sub>opt</sub>*
|
||||
|
||||
  *DeclarationModuleElements:*
|
||||
   *DeclarationModuleElement*
|
||||
   *DeclarationModuleElements* *DeclarationModuleElement*
|
||||
|
||||
  *DeclarationModuleElement:*
|
||||
   *DeclarationElement*
|
||||
   *ImportDeclaration*
|
||||
   *ImportAliasDeclaration*
|
||||
   *ExportDeclarationElement*
|
||||
   *ExportDefaultDeclarationElement*
|
||||
   *ExportListDeclaration*
|
||||
   *ExportAssignment*
|
||||
|
||||
Initialization order of modules is determined by the module loader being used and is not specified by the TypeScript language. However, it is generally the case that non-circularly dependent modules are automatically loaded and initialized in the correct order.
|
||||
|
||||
Modules can additionally be declared using *AmbientModuleDeclarations* in declaration scripts that directly specify the module names as string literals. This is described further in section [#ambient-module-declarations]<!--12.2-->.
|
||||
|
||||
Below is an example of two modules written in separate source files:
|
||||
|
||||
```TypeScript
|
||||
// -------- main.ts --------
|
||||
import { message } from "./log";
|
||||
message("hello");
|
||||
|
||||
// -------- log.ts --------
|
||||
export function message(s: string) {
|
||||
console.log(s);
|
||||
}
|
||||
```
|
||||
|
||||
The import declaration in the 'main' module references the 'log' module and compiling the 'main.ts' file causes the 'log.ts' file to also be compiled as part of the program.
|
||||
|
||||
TypeScript supports multiple patterns of JavaScript code generation for modules:
|
||||
|
||||
* CommonJS. This format is used by server frameworks such as node.js.
|
||||
* AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS.
|
||||
* UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders.
|
||||
* System. This format is used to represent ECMAScript 2015 semantics with high fidelity in down-level environments.
|
||||
|
||||
The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code.
|
||||
|
||||
### Module Names { #module-names }
|
||||
|
||||
Modules are identified and referenced using module names. The following definition is aligned with that provided in the [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) 1.0 specification.
|
||||
|
||||
* A module name is a string of terms delimited by forward slashes.
|
||||
* Module names may not have file-name extensions like ".js".
|
||||
* Module names may be relative or top-level. A module name is relative if the first term is "." or "..".
|
||||
* Top-level names are resolved off the conceptual module name space root.
|
||||
* Relative names are resolved relative to the name of the module in which they occur.
|
||||
|
||||
For purposes of resolving module references, TypeScript associates a file path with every module. The file path is simply the path of the module's source file without the file extension. For example, a module contained in the source file 'C:\src\lib\io.ts' has the file path 'C:/src/lib/io' and a module contained in the source file 'C:\src\ui\editor.d.ts' has the file path 'C:/src/ui/editor'.
|
||||
|
||||
A module name in an import declaration is resolved as follows:
|
||||
|
||||
* If the import declaration specifies a relative module name, the name is resolved relative to the directory of the referencing module's file path. The program must contain a module with the resulting file path or otherwise an error occurs. For example, in a module with the file path 'C:/src/ui/main', the module names './editor' and '../lib/io' reference modules with the file paths 'C:/src/ui/editor' and 'C:/src/lib/io'.
|
||||
* If the import declaration specifies a top-level module name and the program contains an *AmbientModuleDeclaration* (section [#ambient-module-declarations]<!--12.2-->) with a string literal that specifies that exact name, then the import declaration references that ambient module.
|
||||
* If the import declaration specifies a top-level module name and the program contains no *AmbientModuleDeclaration* (section [#ambient-module-declarations]<!--12.2-->) with a string literal that specifies that exact name, the name is resolved in a host dependent manner (for example by considering the name relative to a module name space root). If a matching module cannot be found an error occurs.
|
||||
|
||||
### Import Declarations { #import-declarations }
|
||||
|
||||
Import declarations are used to import entities from other modules and provide bindings for them in the current module.
|
||||
|
||||
An import declaration of the form
|
||||
|
||||
```TypeScript
|
||||
import * as m from "mod";
|
||||
```
|
||||
|
||||
imports the module with the given name and creates a local binding for the module itself. The local binding is classified as a value (representing the module instance) and a namespace (representing a container of types and namespaces).
|
||||
|
||||
An import declaration of the form
|
||||
|
||||
```TypeScript
|
||||
import { x, y, z } from "mod";
|
||||
```
|
||||
|
||||
imports a given module and creates local bindings for a specified list of exported members of the module. The specified names must each reference an entity in the export member set ([#export-member-set]<!--11.3.4.4-->) of the given module. The local bindings have the same names and classifications as the entities they represent unless `as` clauses are used to that specify different local names:
|
||||
|
||||
```TypeScript
|
||||
import { x as a, y as b } from "mod";
|
||||
```
|
||||
|
||||
An import declaration of the form
|
||||
|
||||
```TypeScript
|
||||
import d from "mod";
|
||||
```
|
||||
|
||||
is exactly equivalent to the import declaration
|
||||
|
||||
```TypeScript
|
||||
import { default as d } from "mod";
|
||||
```
|
||||
|
||||
An import declaration of the form
|
||||
|
||||
```TypeScript
|
||||
import "mod";
|
||||
```
|
||||
|
||||
imports the given module without creating any local bindings (this is useful only if the imported module has side effects).
|
||||
|
||||
### Import Require Declarations { #import-require-declarations }
|
||||
|
||||
Import require declarations exist for backward compatibility with earlier versions of TypeScript.
|
||||
|
||||
  *ImportRequireDeclaration:*
|
||||
   `import` *BindingIdentifier* `=` `require` `(` *StringLiteral* `)` `;`
|
||||
|
||||
An import require declaration introduces a local identifier that references a given module. The string literal specified in an import require declaration is interpreted as a module name (section [#module-names]<!--11.3.1-->). The local identifier introduced by the declaration becomes an alias for, and is classified exactly like, the entity exported from the referenced module. Specifically, if the referenced module contains no export assignment the identifier is classified as a value and a namespace, and if the referenced module contains an export assignment the identifier is classified exactly like the entity named in the export assignment.
|
||||
|
||||
An import require declaration of the form
|
||||
|
||||
```TypeScript
|
||||
import m = require("mod");
|
||||
```
|
||||
|
||||
is equivalent to the ECMAScript 2015 import declaration
|
||||
|
||||
```TypeScript
|
||||
import * as m from "mod";
|
||||
```
|
||||
|
||||
provided the referenced module contains no export assignment.
|
||||
|
||||
### Export Declarations { #export-declarations }
|
||||
|
||||
An export declaration declares one or more exported module members. The exported members of a module can be imported in other modules using import declarations ([#import-declarations]<!--11.3.2-->).
|
||||
|
||||
#### Export Modifiers { #export-modifiers }
|
||||
|
||||
In the body of a module, a declaration can export the declared entity by including an `export` modifier.
|
||||
|
||||
  *ExportImplementationElement:*
|
||||
   `export` *VariableStatement*
|
||||
   `export` *LexicalDeclaration*
|
||||
   `export` *FunctionDeclaration*
|
||||
   `export` *GeneratorDeclaration*
|
||||
   `export` *ClassDeclaration*
|
||||
   `export` *InterfaceDeclaration*
|
||||
   `export` *TypeAliasDeclaration*
|
||||
   `export` *EnumDeclaration*
|
||||
   `export` *NamespaceDeclaration*
|
||||
   `export` *AmbientDeclaration*
|
||||
   `export` *ImportAliasDeclaration*
|
||||
|
||||
  *ExportDeclarationElement:*
|
||||
   `export` *InterfaceDeclaration*
|
||||
   `export` *TypeAliasDeclaration*
|
||||
   `export` *AmbientDeclaration*
|
||||
   `export` *ImportAliasDeclaration*
|
||||
|
||||
In addition to introducing a name in the local declaration space of the module, an exported declaration introduces the same name with the same classification in the module's export declaration space. For example, the declaration
|
||||
|
||||
```TypeScript
|
||||
export function point(x: number, y: number) {
|
||||
return { x, y };
|
||||
}
|
||||
```
|
||||
|
||||
introduces a local name `point` and an exported name `point` that both reference the function.
|
||||
|
||||
#### Export Default Declarations { #export-default-declarations }
|
||||
|
||||
Export default declarations provide short-hand syntax for exporting an entity named `default`.
|
||||
|
||||
  *ExportDefaultImplementationElement:*
|
||||
   `export` `default` *FunctionDeclaration*
|
||||
   `export` `default` *GeneratorDeclaration*
|
||||
   `export` `default` *ClassDeclaration*
|
||||
   `export` `default` *AssignmentExpression* `;`
|
||||
|
||||
  *ExportDefaultDeclarationElement:*
|
||||
   `export` `default` *AmbientFunctionDeclaration*
|
||||
   `export` `default` *AmbientClassDeclaration*
|
||||
   `export` `default` *IdentifierReference* `;`
|
||||
|
||||
An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for a function, generator, or class introduces a value named `default`, and in the case of a class, a type named `default`, in the containing module's export declaration space. The declaration may optionally specify a local name for the exported function, generator, or class. For example, the declaration
|
||||
|
||||
```TypeScript
|
||||
export default function point(x: number, y: number) {
|
||||
return { x, y };
|
||||
}
|
||||
```
|
||||
|
||||
introduces a local name `point` and an exported name `default` that both reference the function. The declaration is effectively equivalent to
|
||||
|
||||
```TypeScript
|
||||
function point(x: number, y: number) {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
export default point;
|
||||
```
|
||||
|
||||
which again is equivalent to
|
||||
|
||||
```TypeScript
|
||||
function point(x: number, y: number) {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
export { point as default };
|
||||
```
|
||||
|
||||
An *ExportDefaultImplementationElement* or *ExportDefaultDeclarationElement* for an expression consisting of a single identifier must name an entity declared in the current module or the global namespace. The declaration introduces an entity named `default`, with the same classification as the referenced entity, in the containing module's export declaration space. For example, the declarations
|
||||
|
||||
```TypeScript
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function Point(x: number, y: number): Point {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
export default Point;
|
||||
```
|
||||
|
||||
introduce a local name `Point` and an exported name `default`, both with a value and a type meaning.
|
||||
|
||||
An *ExportDefaultImplementationElement* for any expression but a single identifier introduces a value named `default` in the containing module's export declaration space. For example, the declaration
|
||||
|
||||
```TypeScript
|
||||
export default "hello";
|
||||
```
|
||||
|
||||
introduces an exported value named `default` of type string.
|
||||
|
||||
#### Export List Declarations { #export-list-declarations }
|
||||
|
||||
An export list declaration exports one or more entities from the current module or a specified module.
|
||||
|
||||
  *ExportListDeclaration:*
|
||||
   `export` `*` *FromClause* `;`
|
||||
   `export` *ExportClause* *FromClause* `;`
|
||||
   `export` *ExportClause* `;`
|
||||
|
||||
An *ExportListDeclaration* without a *FromClause* exports entities from the current module. In a declaration of the form
|
||||
|
||||
```TypeScript
|
||||
export { x };
|
||||
```
|
||||
|
||||
the name `x` must reference an entity declared in the current module or the global namespace, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space.
|
||||
|
||||
An *ExportListDeclaration* with a *FromClause* re-exports entities from a specified module. In a declaration of the form
|
||||
|
||||
```TypeScript
|
||||
export { x } from "mod";
|
||||
```
|
||||
|
||||
the name `x` must reference an entity in the export member set of the specified module, and the declaration introduces an entity with the same name and meaning in the containing module's export declaration space. No local bindings are created for `x`.
|
||||
|
||||
The *ExportClause* of an *ExportListDeclaration* can specify multiple entities and may optionally specify different names to be used for the exported entities. For example, the declaration
|
||||
|
||||
```TypeScript
|
||||
export { x, y as b, z as c };
|
||||
```
|
||||
|
||||
introduces entities named `x`, `b`, and `c` in the containing module's export declaration space with the same meaning as the local entities named `x`, `y`, and `z` respectively.
|
||||
|
||||
An *ExportListDeclaration* that specifies `*` instead of an *ExportClause* is called an ***export star*** declaration. An export star declaration re-exports all members of a specified module.
|
||||
|
||||
```TypeScript
|
||||
export * from "mod";
|
||||
```
|
||||
|
||||
Explicitly exported members take precedence over members re-exported using export star declarations, as described in the following section.
|
||||
|
||||
#### Export Member Set { #export-member-set }
|
||||
|
||||
The ***export member set*** of a particular module is determined by starting with an empty set of members *E* and an empty set of processed modules *P*, and then processing the module as described below to form the full set of exported members in *E*. Processing a module *M* consists of these steps:
|
||||
|
||||
* Add *M* to *P*.
|
||||
* Add to *E* each member in the export declaration space of *M* with a name that isn't already in *E*.
|
||||
* For each export star declaration in *M*, in order of declaration, process the referenced module if it is not already in *P*.
|
||||
|
||||
A module's ***instance type*** is an object type with a property for each member in the module's export member set that denotes a value.
|
||||
|
||||
If a module contains an export assignment it is an error for the module to also contain export declarations. The two types of exports are mutually exclusive.
|
||||
|
||||
### Export Assignments { #export-assignments }
|
||||
|
||||
Export assignments exist for backward compatibility with earlier versions of TypeScript. An export assignment designates a module member as the entity to be exported in place of the module itself.
|
||||
|
||||
  *ExportAssignment:*
|
||||
   `export` `=` *IdentifierReference* `;`
|
||||
|
||||
A module containing an export assignment can be imported using an import require declaration ([#import-require-declarations]<!--11.3.3-->), and the local alias introduced by the import require declaration then takes on all meanings of the identifier named in the export assignment.
|
||||
|
||||
A module containing an export assignment can also be imported using a regular import declaration ([#import-declarations]<!--11.3.2-->) provided the entity referenced in the export assignment is declared as a namespace or as a variable with a type annotation.
|
||||
|
||||
Assume the following example resides in the file 'point.ts':
|
||||
|
||||
```TypeScript
|
||||
export = Point;
|
||||
|
||||
class Point {
|
||||
constructor(public x: number, public y: number) { }
|
||||
static origin = new Point(0, 0);
|
||||
}
|
||||
```
|
||||
|
||||
When 'point.ts' is imported in another module, the import alias references the exported class and can be used both as a type and as a constructor function:
|
||||
|
||||
```TypeScript
|
||||
import Pt = require("./point");
|
||||
|
||||
var p1 = new Pt(10, 20);
|
||||
var p2 = Pt.origin;
|
||||
```
|
||||
|
||||
Note that there is no requirement that the import alias use the same name as the exported entity.
|
||||
|
||||
### CommonJS Modules { #commonjs-modules }
|
||||
|
||||
The [CommonJS Modules](http://www.commonjs.org/specs/modules/1.0/) definition specifies a methodology for writing JavaScript modules with implied privacy, the ability to import other modules, and the ability to explicitly export members. A CommonJS compliant system provides a 'require' function that can be used to synchronously load other modules to obtain their singleton module instance, as well as an 'exports' variable to which a module can add properties to define its external API.
|
||||
|
||||
The 'main' and 'log' example from section [#modules]<!--11.3--> above generates the following JavaScript code when compiled for the CommonJS Modules pattern:
|
||||
|
||||
File main.js:
|
||||
|
||||
```TypeScript
|
||||
var log_1 = require("./log");
|
||||
log_1.message("hello");
|
||||
```
|
||||
|
||||
File log.js:
|
||||
|
||||
```TypeScript
|
||||
function message(s) {
|
||||
console.log(s);
|
||||
}
|
||||
exports.message = message;
|
||||
```
|
||||
|
||||
A module import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [#import-alias-declarations]<!--10.3-->) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName* or *TypeQueryExpression*, nothing is emitted.
|
||||
|
||||
An example:
|
||||
|
||||
File geometry.ts:
|
||||
|
||||
```TypeScript
|
||||
export interface Point { x: number; y: number };
|
||||
|
||||
export function point(x: number, y: number): Point {
|
||||
return { x, y };
|
||||
}
|
||||
```
|
||||
|
||||
File game.ts:
|
||||
|
||||
```TypeScript
|
||||
import * as g from "./geometry";
|
||||
let p = g.point(10, 20);
|
||||
```
|
||||
|
||||
The 'game' module references the imported 'geometry' module in an expression (through its alias 'g') and a 'require' call is therefore included in the emitted JavaScript:
|
||||
|
||||
```TypeScript
|
||||
var g = require("./geometry");
|
||||
var p = g.point(10, 20);
|
||||
```
|
||||
|
||||
Had the 'game' module instead been written to only reference 'geometry' in a type position
|
||||
|
||||
```TypeScript
|
||||
import * as g from "./geometry";
|
||||
let p: g.Point = { x: 10, y: 20 };
|
||||
```
|
||||
|
||||
the emitted JavaScript would have no dependency on the 'geometry' module and would simply be
|
||||
|
||||
```TypeScript
|
||||
var p = { x: 10, y: 20 };
|
||||
```
|
||||
|
||||
### AMD Modules { #amd-modules }
|
||||
|
||||
The [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) (AMD) specification extends the CommonJS Modules specification with a pattern for authoring asynchronously loadable modules with associated dependencies. Using the AMD pattern, modules are emitted as calls to a global 'define' function taking an array of dependencies, specified as module names, and a callback function containing the module body. The global 'define' function is provided by including an AMD compliant loader in the application. The loader arranges to asynchronously load the module's dependencies and, upon completion, calls the callback function passing resolved module instances as arguments in the order they were listed in the dependency array.
|
||||
|
||||
The "main" and "log" example from above generates the following JavaScript code when compiled for the AMD pattern.
|
||||
|
||||
File main.js:
|
||||
|
||||
```TypeScript
|
||||
define(["require", "exports", "./log"], function(require, exports, log_1) {
|
||||
log_1.message("hello");
|
||||
}
|
||||
```
|
||||
|
||||
File log.js:
|
||||
|
||||
```TypeScript
|
||||
define(["require", "exports"], function(require, exports) {
|
||||
function message(s) {
|
||||
console.log(s);
|
||||
}
|
||||
exports.message = message;
|
||||
}
|
||||
```
|
||||
|
||||
The special 'require' and 'exports' dependencies are always present. Additional entries are added to the dependencies array and the parameter list as required to represent imported modules. Similar to the code generation for CommonJS Modules, a dependency entry is generated for a particular imported module only if the imported module is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName*, no dependency is generated for that module.
|
||||
|
||||
<br/>
|
||||
|
||||
301
doc/spec/Statements.md
Normal file
301
doc/spec/Statements.md
Normal file
@@ -0,0 +1,301 @@
|
||||
|
||||
# Statements { #statements }
|
||||
|
||||
This chapter describes the static type checking TypeScript provides for JavaScript statements. TypeScript itself does not introduce any new statement constructs, but it does extend the grammar for local declarations to include interface, type alias, and enum declarations.
|
||||
|
||||
## Blocks { #blocks }
|
||||
|
||||
Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 2015 grammar).
|
||||
|
||||
  *Declaration:* *( Modified )*
|
||||
   …
|
||||
   *InterfaceDeclaration*
|
||||
   *TypeAliasDeclaration*
|
||||
   *EnumDeclaration*
|
||||
|
||||
Local class, interface, type alias, and enum declarations are block scoped, similar to let and const declarations.
|
||||
|
||||
## Variable Statements { #variable-statements }
|
||||
|
||||
Variable statements are extended to include optional type annotations.
|
||||
|
||||
  *VariableDeclaration:* *( Modified )*
|
||||
   *SimpleVariableDeclaration*
|
||||
   *DestructuringVariableDeclaration*
|
||||
|
||||
A variable declaration is either a simple variable declaration or a destructuring variable declaration.
|
||||
|
||||
### Simple Variable Declarations { #simple-variable-declarations }
|
||||
|
||||
A ***simple variable declaration*** introduces a single named variable and optionally assigns it an initial value.
|
||||
|
||||
  *SimpleVariableDeclaration:*
|
||||
   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>*
|
||||
|
||||
The type *T* of a variable introduced by a simple variable declaration is determined as follows:
|
||||
|
||||
* If the declaration includes a type annotation, *T* is that type.
|
||||
* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [#widened-types]<!--3.12-->) of the type of the initializer expression.
|
||||
* Otherwise, *T* is the Any type.
|
||||
|
||||
When a variable declaration specifies both a type annotation and an initializer expression, the type of the initializer expression is required to be assignable to (section [#assignment-compatibility]<!--3.11.4-->) the type given in the type annotation.
|
||||
|
||||
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.
|
||||
|
||||
When a variable declaration has a type annotation, it is an error for that type annotation to use the `typeof` operator to reference the variable being declared.
|
||||
|
||||
Below are some examples of simple variable declarations and their associated types.
|
||||
|
||||
```TypeScript
|
||||
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'.
|
||||
|
||||
```TypeScript
|
||||
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; }'.
|
||||
|
||||
```TypeScript
|
||||
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 };
|
||||
```
|
||||
|
||||
### Destructuring Variable Declarations { #destructuring-variable-declarations }
|
||||
|
||||
A ***destructuring variable declaration*** introduces zero or more named variables and initializes them with values extracted from properties of an object or elements of an array.
|
||||
|
||||
  *DestructuringVariableDeclaration:*
|
||||
   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer*
|
||||
|
||||
Each binding property or element that specifies an identifier introduces a variable by that name. The type of the variable is the widened form (section [#widened-types]<!--3.12-->) of the type associated with the binding property or element, as defined in the following.
|
||||
|
||||
*TODO: Document destructuring an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array*.
|
||||
|
||||
The type *T* associated with a destructuring variable declaration is determined as follows:
|
||||
|
||||
* If the declaration includes a type annotation, *T* is that type.
|
||||
* Otherwise, if the declaration includes an initializer expression, *T* is the type of that initializer expression.
|
||||
* Otherwise, *T* is the Any type.
|
||||
|
||||
The type *T* associated with a binding property is determined as follows:
|
||||
|
||||
* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element.
|
||||
* If *S* is the Any type:
|
||||
* If the binding property specifies an initializer expression, *T* is the type of that initializer expression.
|
||||
* Otherwise, *T* is the Any type.
|
||||
* Let *P* be the property name specified in the binding property.
|
||||
* If *S* has an apparent property with the name *P*, *T* is the type of that property.
|
||||
* Otherwise, if *S* has a numeric index signature and *P* is a numerical name, *T* is the type of the numeric index signature.
|
||||
* Otherwise, if *S* has a string index signature, *T* is the type of the string index signature.
|
||||
* Otherwise, no type is associated with the binding property and an error occurs.
|
||||
|
||||
The type *T* associated with a binding element is determined as follows:
|
||||
|
||||
* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element.
|
||||
* If *S* is the Any type:
|
||||
* If the binding element specifies an initializer expression, *T* is the type of that initializer expression.
|
||||
* Otherwise, *T* is the Any type.
|
||||
* If *S* is not an array-like type (section [#array-types]<!--3.3.2-->), no type is associated with the binding property and an error occurs.
|
||||
* If the binding element is a rest element, *T* is an array type with an element type *E*, where *E* is the type of the numeric index signature of *S*.
|
||||
* Otherwise, if *S* is a tuple-like type (section [#tuple-types]<!--3.3.3-->):
|
||||
* Let *N* be the zero-based index of the binding element in the array binding pattern.
|
||||
* If *S* has a property with the numerical name *N*, *T* is the type of that property.
|
||||
* Otherwise, no type is associated with the binding element and an error occurs.
|
||||
* Otherwise, if *S* has a numeric index signature, *T* is the type of the numeric index signature.
|
||||
* Otherwise, no type is associated with the binding element and an error occurs.
|
||||
|
||||
When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element.
|
||||
|
||||
*TODO: Update rules to reflect [improved checking of destructuring with literal initializers](https://github.com/Microsoft/TypeScript/pull/4598)*.
|
||||
|
||||
When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code.
|
||||
|
||||
When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form
|
||||
|
||||
```TypeScript
|
||||
var { x, p: y, q: z = false } = getSomeObject();
|
||||
```
|
||||
|
||||
is rewritten to the simple variable declarations
|
||||
|
||||
```TypeScript
|
||||
var _a = getSomeObject(),
|
||||
x = _a.x,
|
||||
y = _a.p,
|
||||
_b = _a.q,
|
||||
z = _b === void 0 ? false : _b;
|
||||
```
|
||||
|
||||
The '_a' and '_b' temporary variables exist to ensure the assigned expression is evaluated only once, and the expression 'void 0' simply denotes the JavaScript value 'undefined'.
|
||||
|
||||
Similarly, an array destructuring declaration of the form
|
||||
|
||||
```TypeScript
|
||||
var [x, y, z = 10] = getSomeArray();
|
||||
```
|
||||
|
||||
is rewritten to the simple variable declarations
|
||||
|
||||
```TypeScript
|
||||
var _a = getSomeArray(),
|
||||
x = _a[0],
|
||||
y = _a[1],
|
||||
_b = _a[2],
|
||||
z = _b === void 0 ? 10 : _b;
|
||||
```
|
||||
|
||||
Combining both forms of destructuring, the example
|
||||
|
||||
```TypeScript
|
||||
var { x, p: [y, z = 10] = getSomeArray() } = getSomeObject();
|
||||
```
|
||||
|
||||
is rewritten to
|
||||
|
||||
```TypeScript
|
||||
var _a = getSomeObject(),
|
||||
x = _a.x,
|
||||
_b = _a.p,
|
||||
_c = _b === void 0 ? getSomeArray() : _b,
|
||||
y = _c[0],
|
||||
_d = _c[1],
|
||||
z = _d === void 0 ? 10 : _d;
|
||||
```
|
||||
|
||||
### Implied Type { #implied-type }
|
||||
|
||||
A variable, parameter, binding property, or binding element declaration that specifies a binding pattern has an ***implied type*** which is determined as follows:
|
||||
|
||||
* If the declaration specifies an object binding pattern, the implied type is an object type with a set of properties corresponding to the specified binding property declarations. The type of each property is the type implied by its binding property declaration, and a property is optional when its binding property declaration specifies an initializer expression.
|
||||
* If the declaration specifies an array binding pattern without a rest element, the implied type is a tuple type with elements corresponding to the specified binding element declarations. The type of each element is the type implied by its binding element declaration.
|
||||
* If the declaration specifies an array binding pattern with a rest element, the implied type is an array type with an element type of Any.
|
||||
|
||||
The implied type of a binding property or binding element declaration is
|
||||
|
||||
* the type of the declaration's initializer expression, if any, or otherwise
|
||||
* the implied type of the binding pattern specified in the declaration, if any, or otherwise
|
||||
* the type Any.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
function f({ a, b = "hello", c = 1 }) { ... }
|
||||
```
|
||||
|
||||
the implied type of the binding pattern in the function's parameter is '{ a: any; b?: string; c?: number; }'. Since the parameter has no type annotation, this becomes the type of the parameter.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
var [a, b, c] = [1, "hello", true];
|
||||
```
|
||||
|
||||
the array literal initializer expression is contextually typed by the implied type of the binding pattern, specifically the tuple type '[any, any, any]'. Because the contextual type is a tuple type, the resulting type of the array literal is the tuple type '[number, string, boolean]', and the destructuring declaration thus gives the types number, string, and boolean to a, b, and c respectively.
|
||||
|
||||
## Let and Const Declarations { #let-and-const-declarations }
|
||||
|
||||
Let and const declarations are exended to include optional type annotations.
|
||||
|
||||
  *LexicalBinding:* *( Modified )*
|
||||
   *SimpleLexicalBinding*
|
||||
   *DestructuringLexicalBinding*
|
||||
|
||||
  *SimpleLexicalBinding:*
|
||||
   *BindingIdentifier* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>*
|
||||
|
||||
  *DestructuringLexicalBinding:*
|
||||
   *BindingPattern* *TypeAnnotation<sub>opt</sub>* *Initializer<sub>opt</sub>*
|
||||
|
||||
*TODO: Document scoping and types of [let and const declarations](https://github.com/Microsoft/TypeScript/pull/904)*.
|
||||
|
||||
## If, Do, and While Statements { #if-do-and-while-statements }
|
||||
|
||||
Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean).
|
||||
|
||||
## For Statements { #for-statements }
|
||||
|
||||
Variable declarations in 'for' statements are extended in the same manner as variable declarations in variable statements (section [#variable-statements]<!--5.2-->).
|
||||
|
||||
## For-In Statements { #for-in-statements }
|
||||
|
||||
In a 'for-in' statement of the form
|
||||
|
||||
```TypeScript
|
||||
for (v in expr) statement
|
||||
```
|
||||
|
||||
*v* must be an expression classified as a reference of type Any or the String primitive type, and *expr* must be an expression of type Any, an object type, or a type parameter type.
|
||||
|
||||
In a 'for-in' statement of the form
|
||||
|
||||
```TypeScript
|
||||
for (var v in expr) statement
|
||||
```
|
||||
|
||||
*v* must be a variable declaration without a type annotation that declares a variable of type Any, and *expr* must be an expression of type Any, an object type, or a type parameter type.
|
||||
|
||||
## For-Of Statements { #for-of-statements }
|
||||
|
||||
*TODO: Document [for-of statements](https://github.com/Microsoft/TypeScript/issues/7)*.
|
||||
|
||||
## Continue Statements { #continue-statements }
|
||||
|
||||
A 'continue' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') statement. When a 'continue' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) iteration statement.
|
||||
|
||||
## Break Statements { #break-statements }
|
||||
|
||||
A 'break' statement is required to be nested, directly or indirectly (but not crossing function boundaries), within an iteration ('do', 'while', 'for', or 'for-in') or 'switch' statement. When a 'break' statement includes a target label, that target label must appear in the label set of an enclosing (but not crossing function boundaries) statement.
|
||||
|
||||
## Return Statements { #return-statements }
|
||||
|
||||
It is an error for a 'return' statement to occur outside a function body. Specifically, 'return' statements are not permitted at the global level or in namespace bodies.
|
||||
|
||||
A 'return' statement without an expression returns the value 'undefined' and is permitted in the body of any function, regardless of the return type of the function.
|
||||
|
||||
When a 'return' statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section [#contextually-typed-expressions]<!--4.23-->) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type *T*, *Expr* is contextually typed by *T*'s return type.
|
||||
|
||||
In a function implementation without a return type annotation, the return type is inferred from the 'return' statements in the function body, as described in section [#function-implementations]<!--6.3-->.
|
||||
|
||||
In the example
|
||||
|
||||
```TypeScript
|
||||
function f(): (x: string) => number {
|
||||
return s => s.length;
|
||||
}
|
||||
```
|
||||
|
||||
the arrow expression in the 'return' statement is contextually typed by the return type of 'f', thus giving type 'string' to 's'.
|
||||
|
||||
## With Statements { #with-statements }
|
||||
|
||||
Use of the 'with' statement in TypeScript is an error, as is the case in ECMAScript 5's strict mode. Furthermore, within the body of a 'with' statement, TypeScript considers every identifier occurring in an expression (section [#identifiers]<!--4.3-->) to be of the Any type regardless of its declared type. Because the 'with' statement puts a statically unknown set of identifiers in scope in front of those that are statically known, it is not possible to meaningfully assign a static type to any identifier.
|
||||
|
||||
## Switch Statements { #switch-statements }
|
||||
|
||||
In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from (section [#assignment-compatibility]<!--3.11.4-->) the type of the 'switch' expression.
|
||||
|
||||
## Throw Statements { #throw-statements }
|
||||
|
||||
The expression specified in a 'throw' statement can be of any type.
|
||||
|
||||
## Try Statements { #try-statements }
|
||||
|
||||
The variable introduced by a 'catch' clause of a 'try' statement is always of type Any. It is not possible to include a type annotation in a 'catch' clause.
|
||||
|
||||
<br/>
|
||||
1465
doc/spec/Types.md
Normal file
1465
doc/spec/Types.md
Normal file
File diff suppressed because it is too large
Load Diff
BIN
doc/spec/images/image1.png
Normal file
BIN
doc/spec/images/image1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
BIN
doc/spec/images/image2.png
Normal file
BIN
doc/spec/images/image2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
BIN
doc/spec/images/image3.png
Normal file
BIN
doc/spec/images/image3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.9 KiB |
BIN
doc/spec/images/image4.png
Normal file
BIN
doc/spec/images/image4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
14
doc/spec/index.md
Normal file
14
doc/spec/index.md
Normal file
@@ -0,0 +1,14 @@
|
||||
[INCLUDE="Front Matter.md"]
|
||||
[INCLUDE="Intro.md"]
|
||||
[INCLUDE="Basic Concepts.md"]
|
||||
[INCLUDE="Types.md"]
|
||||
[INCLUDE="Expressions.md"]
|
||||
[INCLUDE="Statements.md"]
|
||||
[INCLUDE="Functions.md"]
|
||||
[INCLUDE="Interfaces.md"]
|
||||
[INCLUDE="Classes.md"]
|
||||
[INCLUDE="Enums.md"]
|
||||
[INCLUDE="Namespaces.md"]
|
||||
[INCLUDE="Scripts and Modules.md"]
|
||||
[INCLUDE="Ambients.md"]
|
||||
[INCLUDE="Grammar.md"]
|
||||
Reference in New Issue
Block a user