TypeScript
TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development. TypeScript’s static compile-time type system closely models the dynamic run-time type system of JavaScript, allowing programmers to accurately express the type relationships that are expected to exist when their programs run and have those assumptions pre-validated by the TypeScript compiler. TypeScript’s type analysis occurs entirely at compile-time and adds no run-time overhead to program execution.
All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.
The primitive types are the Number, Boolean, String, Void, Null, and Undefined types along with user defined enum types. The number, boolean, string, and void keywords reference the Number, Boolean, String, and Void primitive types respectively. The Void type exists purely to indicate the absence of a value, such as in a function with no return value. It is not possible to explicitly reference the Null and Undefined types—only values of those types can be referenced, using the null and undefined literals.
The object types are all class, interface, array, and literal types. Class and interface types are introduced through class and interface declarations and are referenced by the name given to them in their declarations. Class and interface types may be generic types which have one or more type parameters. Literal types are written as object, array, function, or constructor type literals and are used to compose new types from other types.
Declarations of modules, classes, properties, functions, variables and other language entities associate types with those entities. The mechanism by which a type is formed and associated with a language entity depends on the particular kind of entity. For example, a module declaration associates the module with an anonymous type containing a set of properties corresponding to the exported variables and functions in the module, and a function declaration associates the function with an anonymous type containing a call signature corresponding to the parameters and return type of the function. Types can be associated with variables through explicit type annotations, such as
var x: number;
or through implicit type inference, as in
var x = 1;
which infers the type of ‘x’ to be the Number primitive type because that is the type of the value used to initialize ‘x’.
The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.
The any keyword references the Any type. In general, in places where a type is not explicitly provided and TypeScript cannot infer one, the Any type is assumed.
The Any type is a supertype of all types.
Some examples:
var x: any;
// Explicitly typed
var y; // Same as y: any
var z: { a; b; }; // Same as z: { a: any; b: any; }
function f(x) { // Same
as f(x: any): void
console.log(x);
}
The primitive types are the Number, Boolean, String, Void, Null, and Undefined types and all user defined enum types.
The Number primitive type corresponds to the similarly named JavaScript primitive type and represents double-precision 64-bit format IEEE 754 floating point values.
The number keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), the Number primitive type behaves as an object type with the same properties as the global interface type ‘Number’.
Some examples:
var x: number;
// Explicitly typed
var y = 0; // Same as y: number = 0
var z = 123.456; // Same as z: number = 123.456
var s = z.toFixed(2); // Property of Number interface
The Boolean primitive type corresponds to the similarly named JavaScript primitive type and represents logical values that are either true or false.
The boolean keyword references the Boolean primitive type and the true and false literals reference the two Boolean truth values.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), the Boolean primitive type behaves as an object type with the same properties as the global interface type ‘Boolean’.
Some examples:
var b: boolean;
// Explicitly typed
var yes = true; // Same as yes: boolean = true
var no = false; // Same as no: boolean = false
The String primitive type corresponds to the similarly named JavaScript primitive type and represents sequences of characters stored as Unicode UTF-16 code units.
The string keyword references the String primitive type and string literals may be used to write values of the String primitive type.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), the String primitive type behaves as an object type with the same properties as the global interface type ‘String’.
Some examples:
var s: string;
// Explicitly typed
var empty = ""; // Same as empty: string = ""
var abc = 'abc'; // Same as abc: string = "abc"
var c = abc.charAt(2); // Property of String interface
The Void type, referenced by the void keyword, represents the absence of a value and is used as the return type of functions with no return value.
The only possible values for the Void type are null and undefined. The Void type is a subtype of the Any type and a supertype of the Null and Undefined types, but otherwise Void is unrelated to all other types.
NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters.
The Null type corresponds to the similarly named JavaScript primitive type and is the type of the null literal.
The null literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself.
The Null type is a subtype of all types, except the Undefined type. This means that null is considered a valid value for all primitive types, object types, and type parameters, including even the Number and Boolean primitive types.
Some examples:
var n: number = null; // Primitives can be null
var x = null; // Same as x: any = null
var e: Null; // Error, can't reference Null type
The Undefined type corresponds to the similarly named JavaScript primitive type and is the type of the undefined literal.
The undefined literal denotes the value given to all uninitialized variables and is the one and only value of the Undefined type. It is not possible to directly reference the Undefined type itself.
The undefined type is a subtype of all types. This means that undefined is considered a valid value for all primitive types, object types, and type parameters.
Some examples:
var n: number;
// Same as n: number = undefined
var x = undefined; // Same as x: any = undefined
var e: Undefined; // Error, can't reference Undefined type
Enum types are distinct user defined subtypes of the Number primitive type. Enum types are declared using enum declarations (section 9.1) and referenced using type references (section 3.6.2).
Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other.
Specialized signatures (section 3.7.2.4) permit string literals to be used as types in parameter type annotations. String literal types are permitted only in that context and nowhere else.
All string literal types are subtypes of the String primitive type.
The object types include references to class and interface types as well as anonymous object types created by a number of constructs such as object literals, function declarations, and module declarations. Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members.
Type references (section 3.6.2) to class and interface types are classified as object types. Type references to generic class and interface types include type arguments that are substituted for the type parameters of the class or interface to produce an actual object type.
Array types represent JavaScript arrays. Array types are type references (section 3.6.2) created from the generic interface type ‘Array’ in the global module. Array type literals (section 3.6.4) provide a shorthand notation for creating such references.
Array literals (section 4.6) may be used to create values of array types.
Several constructs in the TypeScript language introduce new anonymous object types:
· Function and constructor type literals (section 3.6.4).
· Object type literals (section 3.7).
· Object literals (section 4.5).
· Function expressions (section 4.9) and function declarations (6.1).
· Constructor function types created by class declarations (section 8.2.5).
· Module instance types created by module declarations (section 10.3).
Every object type is composed from zero or more of the following kinds of members:
· Properties, which define the names and types of the properties of objects of the given type. Property names are unique within their type.
· Call signatures, which define the possible parameter lists and return types associated with applying call operations to objects of the given type.
· Construct signatures, which define the possible parameter lists and return types associated with applying the new operator to objects of the given type.
· Index signatures, which define type constraints for properties in the given type.
Properties are either public or private and are either required or optional:
· Properties in a class declaration may be designated public or private, while properties declared in other contexts are always considered public. Private members are only accessible within the class body containing their declaration, as described in section 8.2.2, and private properties match only themselves in subtype and assignment compatibility checks, as described in section 3.8.
· Properties in an object type literal or interface declaration may be designated required or optional, while properties declared in other contexts are always considered required. Properties that are optional in the target type of an assignment may be omitted from source objects, as described in section 3.8.3.
Call and construct signatures may be specialized (section 3.7.2.4) by including parameters with string literal types. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized.
For purposes of determining type relationships (section 3.8) and accessing properties (section 4.10), object types appear to have certain additional members:
· Every object type appears to have the members of the global interface type ‘Object’ unless those members are hidden by members in the object type.
· An object type with one or more call or construct signatures appears to have the members of the global interface type ‘Function’ unless those members are hidden by members in the object type.
Object type members hide ‘Object’ or ‘Function’ interface members in the following manner:
· A property hides an ‘Object’ or ‘Function’ property with the same name.
· A call signature hides an ‘Object’ or ‘Function’ call signature with the same number of parameters and identical parameter types in the respective positions.
· A construct signature hides an ‘Object’ or ‘Function’ construct signature with the same number of parameters and identical parameter types in the respective positions.
· An index signature hides an ‘Object’ or ‘Function’ index signature with the same parameter type.
In effect, object types are subtypes of the ‘Object’ or ‘Function’ interface unless the object types define members that are incompatible with those of the ‘Object’ or ‘Function’ interface—which, for example, occurs if an object type defines a property with the same name as a property in the ‘Object’ or ‘Function’ interface but with a type that isn’t a subtype of that in the ‘Object’ or ‘Function’ interface.
Some examples:
var o: Object = { x: 10,
y: 20 }; // Ok
var f: Function = (x: number) => x * x; // Ok
var err: Object = { toString: 0 }; // Error, incompatible toString
A type parameter represents an actual type that the parameter is bound to in a generic type reference or a generic function call. Type parameters have constraints that establish upper bounds for their actual type arguments.
Since a type parameter represents a multitude of different type arguments, type parameters have certain restrictions compared to other types. In particular, a type parameter cannot be used as a base class or interface.
For purposes of determining type relationships (section 3.8), type parameters appear to be subtypes of the constraint specified in their declaration (or subtypes of ‘Object’ when no constraint was specified). Likewise, for purposes of accessing properties (section 4.10), type parameters appear to have the members of their declared constraint, but no other members.
Class, interface, and enum types are named types that are introduced through class declarations (section 8.1), interface declarations (section 7.1), and enum declarations (9.1). Class and interface types may have type parameters and are then called generic types. Conversely, named types without type parameters are called non-generic types.
Interface declarations only introduce named types, whereas class declarations introduce named types and constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can’t declare optional members and interfaces can’t declare private members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations.
Named types are referenced through type references (section 3.6.2) that specify a type name and, if applicable, the type arguments to be substituted for the type parameters of the named type.
Named types are technically not types—only references to named types are. This distinction is particularly evident with generic types: Generic types are “templates” from which multiple actual types can be created by writing type references that supply type arguments to substitute in place of the generic type’s type parameters. Only once this substitution takes place does a generic type denote an actual type.
TypeScript has a structural type system, and therefore a type created from a reference to a generic type is indistinguishable from an equivalent manually written expansion. For example, given the declaration
interface Pair<T1, T2> { first: T1; second: T2; }
the type reference
Pair<string, Entity>
is indistinguishable from the type
{ first: string; second: Entity; }
Class, interface, and function declarations may optionally include lists of type parameters enclosed in < and > brackets. Type parameters are also permitted in call signatures of object, function, and constructor type literals.
TypeParameters:
< TypeParameterList >
TypeParameterList:
TypeParameter
TypeParameterList , TypeParameter
TypeParameter:
Identifier Constraintopt
Constraint:
extends Type
Type parameter names must be unique. A compile-time error occurs if two or more type parameters in the same TypeParameterList have the same name.
The scope of a type parameter extends over the entire declaration with which the type parameter list is associated, the only exception being static member declarations in classes.
Each type parameter has an associated type parameter constraint that establishes an upper bound for type arguments: A type argument for a given type parameter must be assignable to the type specified in the type parameter constraint. Omitting a constraint corresponds to specifying the global interface type ‘Object’.
Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter.
Generic types are permitted to directly or indirectly reference themselves in a recursive fashion as long as such references do not generate an infinite series of new types. Specifically, within a generic type G < T1 , T2 , … , Tn > and the types referenced by it, it is an error to reference G with a type argument that wraps any of G’s own type parameters (i.e. a type argument that wraps any Tx). A type parameter is said to be wrapped by a particular type when it is referenced, directly or indirectly, within that type.
Consider the following example:
interface List<T> {
data: T;
next: List<T>;
owner: List<List<T>>; // Error, recursive reference with wrapped T
}
In the example the ‘owner’ property creates an infinite series of new types that wrap a ‘List<T>’ around each previous ‘List<T>’. Such generative recursion is prohibited by the rule above.
Note that it would be perfectly fine for the ‘owner’ property to have type ‘List<List<Object>>’ or any other type with a nested reference to ‘List’ that doesn’t reference ‘T’.
TODO: The restriction on generative recursion is likely to be removed.
Each named type has an associated actual type known as the instance type. For a non-generic type, the instance type is simply a type reference to the non-generic type. For a generic type, the instance type is formed by creating a type reference from the generic type where each of the supplied type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the generic type. Within the constructor and member functions of a class, the type of this is the instance type of the class.
The following example illustrates the concept of an instance type:
class G<T> { // Introduce type parameter T
self: G<T>; // Use T as type argument to form instance type
f() {
this.self = this; // self and this are both of
type G<T>
}
}
Types are specified either by referencing their keyword or name, by querying expression types, or by writing type literals which compose other types into new types.
Type:
PredefinedType
TypeReference
TypeQuery
TypeLiteral
The any, number, boolean, string, and void keywords reference the Any type and the Number, Boolean, String, and Void primitive types respectively.
PredefinedType:
any
number
boolean
string
void
The predefined type keywords are reserved and cannot be used as names of user defined types.
A type reference references a named type or type parameter through its name and, in the case of a generic type, supplies a type argument list.
TypeReference:
TypeName TypeArgumentsopt
TypeName:
Identifier
ModuleName . Identifier
ModuleName:
Identifier
ModuleName . Identifier
A TypeReference consists of a TypeName that a references a named type or type parameter. A reference to a generic type must be followed by a list of TypeArguments.
Resolution of a TypeName consisting of a single identifier is described in section 2.4.
Resolution of a TypeName of the form M.N, where M is a ModuleName and N is an Identifier, proceeds by first resolving the module name M. If the resolution of M is successful and the resulting module contains an exported named type N, then M.N refers to that member. Otherwise, M.N is undefined.
Resolution of a ModuleName consisting of a single identifier is described in section 2.4.
Resolution of a ModuleName of the form M.N, where M is a ModuleName and N is an Identifier, proceeds by first resolving the module name M. If the resolution of M is successful and the resulting module contains an exported module member N, then M.N refers to that member. Otherwise, M.N is undefined.
A type reference to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas.
TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument
TypeArgumentList , TypeArgument
TypeArgument:
Type
A type reference to a generic type is required to specify exactly one type argument for each type parameter of the referenced generic type. Each type argument must be assignable to (section 3.8.3) the constraint of the corresponding type parameter or otherwise an error occurs. An example:
interface A { a: string; }
interface B extends A { b: string; }
interface C extends B { c: string; }
interface G<T, U extends B>
{
x: T;
y: U;
}
var v1: G<A, C>; // Ok
var v2: G<{ a: string }, C>; // Ok, equivalent to G<A, C>
var v3: G<A, A>; // Error, A not valid argument for U
var v4: G<G<A, B>,
C>; // Ok
var v5: G<any, any>; // Ok
var v6: G<any>; // Error, wrong number of arguments
var v7: G; // Error,
no arguments
A type argument is simply a Type and may itself be a type reference to a generic type, as demonstrated by ‘v4’ in the example above.
A type reference to a generic type G designates a type wherein all occurrences of G’s type parameters have been replaced with the actual type arguments supplied in the type reference. For example, the declaration of ‘v1’ above is equivalent to:
var v1: {
x: { a: string; }
y: { a: string; b: string; c: string };
};
A type query obtains the type of an expression.
TypeQuery:
typeof TypeQueryExpression
TypeQueryExpression:
Identifier
TypeQueryExpression . IdentifierName
A type query consists of the keyword typeof followed by an expression. The expression is restricted to a single identifier or a sequence of identifiers separated by periods. The expression is processed as an identifier expression (section 4.3) or property access expression (section 4.10), the type of which becomes the result. Similar to other static typing constructs, type queries are erased from the generated JavaScript code and add no run-time overhead.
Type queries are useful for capturing anonymous types that are generated by various constructs such as object literals, function declarations, and module declarations. For example:
var a = { x: 10, y: 20 };
var b: typeof a;
Above, ‘b’ is given the same type as ‘a’, namely ‘{ x: number; y: number; }’.
Type literals compose other types into new anonymous types.
TypeLiteral:
ObjectType
ArrayType
FunctionType
ConstructorType
ArrayType:
PredefinedType [ ]
TypeReference [ ]
ObjectType [ ]
ArrayType [ ]
FunctionType:
TypeParametersopt ( ParameterListopt
) => Type
ConstructorType:
new TypeParametersopt (
ParameterListopt ) => Type
Object type literals are the primary form of type literals and are described in section 3.7. Array, function, and constructor type literals are simply shorthand notations for other types:
Type literal |
Equivalent form |
T [ ] |
Array < T > |
< TParams > ( Params ) => Result |
{ < TParams > ( Params ) : Result } |
new < TParams > ( Params ) => Result |
{ new < TParams > ( Params ) : Result } |
As the table above illustrates, an array type literal is shorthand for a reference to the generic interface type ‘Array’ in the global module, a function type literal is shorthand for an object type containing a single call signature, and a constructor type literal is shorthand for an object type containing a single construct signature. Note that function and constructor types with multiple call or construct signatures cannot be written as function or constructor type literals but must instead be written as object type literals.
In order to avoid grammar ambiguities, array type literals permit only a restricted set of notations for the element type. Specifically, an ArrayType cannot start with a TypeQuery, FunctionType, or ConstructorType. To use one of those forms for the element type, an array type must be written using the ‘Array<T>’ notation. For example, the type
() => string[]
denotes a function returning a string array, not an array of functions returning string. The latter can be expressed using ‘Array<T>’ notation
Array<() => string>
or by writing the element type as an object type literal
{ (): string }[]
An object type literal defines an object type by specifying the set of members that are statically considered to be present in instances of the type. Object type literals can be given names using interface declarations but are otherwise anonymous.
ObjectType:
{ TypeBodyopt }
TypeBody:
TypeMemberList ;opt
TypeMemberList:
TypeMember
TypeMemberList ; TypeMember
TypeMember:
PropertySignature
CallSignature
ConstructSignature
IndexSignature
MethodSignature
The members of an object type literal are specified as a combination of property, call, construct, index, and method signatures. The signatures are separated by semicolons and enclosed in curly braces.
A property signature declares the name and type of a property member.
PropertySignature:
PropertyName ?opt
TypeAnnotationopt
PropertyName:
IdentifierName
StringLiteral
NumericLiteral
The PropertyName production, reproduced above from the ECMAScript grammar, permits a property name to be any identifier (including a reserved word), a string literal, or a numeric literal. String literals can be used to give properties names that are not valid identifiers, such as names containing blanks. Numeric literal property names are equivalent to string literal property names with the string representation of the numeric literal, as defined in the ECMAScript specification.
The PropertyName of a property signature must be unique within its containing type. If the property name is followed by a question mark, the property is optional. Otherwise, the property is required.
If a property signature omits a TypeAnnotation, the Any type is assumed.
A call signature defines the type parameters, parameter list, and return type associated with applying a call operation (section 4.12) to an instance of the containing type. A type may overload call operations by defining multiple different call signatures.
CallSignature:
TypeParametersopt ( ParameterListopt
) TypeAnnotationopt
A call signature that includes TypeParameters (section 3.5.1) is called a generic call signature. Conversely, a call signature with no TypeParameters is called a non-generic call signature.
As well as being members of object type literals, call signatures occur in method signatures (section 3.7.5), function expressions (section 4.9), and function declarations (section 6.1).
An object type containing call signatures is said to be a function type.
It is an error for a type to declare multiple call signatures that are considered identical (section 3.8.1) or differ only in their return types.
Type parameters in call signatures provide a mechanism for expressing the relationships of parameter and return types in call operations. For example, a signature might introduce a type parameter and use it as both a parameter type and a return type, in effect describing a function that returns a value of the same type as its argument.
The scope of a type parameter extends over the entire call signature in which the type parameter is introduced. Thus, type parameters may be referenced in type parameter constraints, parameter types, and return type annotations in their associated call signature.
Type arguments for call signature type parameters may be explicitly specified in a call operation or may, when possible, be inferred (section 4.12.2) from the types of the regular arguments in the call.
Some examples of call signatures with type parameters:
<T>(x: T): T |
A function taking an argument of any type, returning a value of that same type. |
<T>(x: T, y: T): T[] |
A function taking two values of the same type, returning an array of that type. |
<T, U>(x: T, y: U): { x: T; y: U; } |
A function taking two arguments of different types, returning an object with properties ‘x’ and ‘y’ of those types. |
<T, U>(a: T[], f: (x: T) => U): U[] |
A function taking an array of one type and a function argument, returning an array of another type, where the function argument takes a value of the first array element type and returns a value of the second array element type. |
A signature’s parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter.
ParameterList:
RequiredParameterList
OptionalParameterList
RestParameter
RequiredParameterList ,
OptionalParameterList
RequiredParameterList , RestParameter
OptionalParameterList , RestParameter
RequiredParameterList ,
OptionalParameterList , RestParameter
RequiredParameterList:
RequiredParameter
RequiredParameterList , RequiredParameter
RequiredParameter:
PublicOrPrivateopt Identifier TypeAnnotationopt
Identifier : StringLiteral
PublicOrPrivate:
public
private
OptionalParameterList:
OptionalParameter
OptionalParameterList , OptionalParameter
OptionalParameter:
PublicOrPrivateopt Identifier ?
TypeAnnotationopt
PublicOrPrivateopt Identifier TypeAnnotationopt
Initialiser
RestParameter:
... Identifier TypeAnnotationopt
Parameter names must be unique. A compile-time error occurs if two or more parameters have the same name.
A parameter is permitted to include a public or private modifier only if it occurs in the parameter list of a ConstructorImplementation (section 8.3.1).
A parameter with a type annotation is considered to be of that type. A type annotation for a rest parameter must denote an array type.
A parameter with no type annotation or initializer is considered to be of type any, unless it is a rest parameter, in which case it is considered to be of type any[].
When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section 3.7.2.4). Specialized signatures are not permitted in conjunction with a function body, i.e. the FunctionExpression, FunctionImplementation, MemberFunctionImplementation, and ConstructorImplementation grammar productions do not permit parameters with string literal types.
A parameter can be marked optional by following its name with a question mark (?) or by including an initializer. The form that includes an initializer is permitted only in conjunction with a function body, i.e. only in a FunctionExpression, FunctionImplementation, MemberFunctionImplementation, or ConstructorImplementation grammar production.
TODO: Rest parameters.
If present, a call signature’s return type annotation specifies the type of the value computed and returned by a call operation. A void return type annotation is used to indicate that a function has no return value.
When a call signature with no return type annotation occurs in a context without a function body, the return type is assumed to be the Any type.
When a call signature with no return type annotation occurs in a context that has a function body (specifically, a function implementation, a member function implementation, or a member accessor declaration), the return type is inferred from the function body as described in section 6.3.
When a parameter type annotation specifies a string literal type (section 3.2.8), the containing signature is considered a specialized signature. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. For example, the declaration
interface Document {
createElement(tagName: string):
HTMLElement;
createElement(tagName: "div"):
HTMLDivElement;
createElement(tagName: "span"):
HTMLSpanElement;
createElement(tagName: "canvas"):
HTMLCanvasElement;
}
states that calls to ‘createElement’ with the string literals “div”, “span”, and “canvas” return values of type ‘HTMLDivElement’, ‘HTMLSpanElement’, and ‘HTMLCanvasElement’ respectively, and that calls with all other string expressions return values of type ‘HTMLElement’. Because string literal types are subtypes of the String primitive type, when a function call argument matches a parameter of a string literal type in a specialized signature, the overload resolution rules (section 4.12.1) give preference to that signature over a similar signature with a regular string parameter.
Every specialized call or construct signature in an object type must be a subtype of at least one non-specialized call or construct signature in the same object type. For example, the ‘createElement’ property in the example above is of a type that contains three specialized signatures, all of which are subtypes of the non-specialized signature in the type.
A construct signature defines the parameter list and return type associated with applying the new operator (section 4.11) to an instance of the containing type. A type may overload new operations by defining multiple construct signatures with different parameter lists.
ConstructSignature:
new TypeParametersopt (
ParameterListopt ) TypeAnnotationopt
The type parameters, parameter list, and return type of a construct signature are subject to the same rules as a call signature.
A type containing construct signatures is said to be a constructor type.
It is an error for a type to declare multiple construct signatures that are considered identical (section 3.8.1) or differ only by their return types.
An index signature defines a type constraint for properties in the containing type.
IndexSignature:
[ Identifier : string ] TypeAnnotation
[ Identifier : number ] TypeAnnotation
There are two kinds of index signatures:
· String index signatures, specified using index type string, define type constraints for all properties and numeric index signatures in the containing type. Specifically, in a type with a string index signature of type T, all properties and numeric index signatures must have types that are subtypes of T.
· Numeric index signatures, specified using index type number, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type T, all numerically named properties must have types that are subtypes of T.
A numerically named property is a property whose name is a valid numeric literal. Specifically, a property with a name N for which ToNumber(N) is not NaN, where ToNumber is the abstract operation defined in ECMAScript specification.
Index signatures affect the determination of the type that results from applying a bracket notation property access to an instance of the containing type, as described in section 4.10.
A method signature is shorthand for declaring a property of a function type.
MethodSignature:
PropertyName ?opt
CallSignature
If the identifier is followed by a question mark, the property is optional. Otherwise, the property is required. Only object type literals and interfaces can declare optional properties.
A method signature of the form
PropName < TypeParamList > ( ParamList ) : ReturnType
is equivalent to the property declaration
PropName : { < TypeParamList > ( ParamList ) : ReturnType }
A literal type may overload a method by declaring multiple method signatures with the same name but differing parameter lists. Overloads must either all be required (question mark omitted) or all be optional (question mark included). A set of overloaded method signatures correspond to a declaration of a single property with a type composed from an equivalent set of call signatures. Specifically
PropName < TypeParamList1 > ( ParamList1 ) : ReturnType1 ;
PropName < TypeParamList2 > ( ParamList2 ) : ReturnType2 ;
…
PropName < TypeParamListn > ( ParamListn ) : ReturnTypen ;
is equivalent to
PropName : {
< TypeParamList1 > ( ParamList1 ) : ReturnType1 ;
< TypeParamList2 > ( ParamList2 ) : ReturnType2 ;
…
< TypeParamListn > ( ParamListn ) : ReturnTypen ; }
In the following example of an object type
{
func1(x: number): number; // Method
signature
func2: (x: number) => number; // Function type literal
func3: { (x: number): number }; // Object type literal
}
the properties ‘func1’, ‘func2’, and ‘func3’ are all of the same type, namely an object type with a single call signature taking a number and returning a number. Likewise, in the object type
{
func4(x: number): number;
func4(s: string): string;
func5: {
(x: number): number;
(s: string): string;
};
}
the properties ‘func4’ and ‘func5’ are of the same type, namely an object type with two call signatures taking and returning number and string respectively.
Types in TypeScript have identity, subtype, supertype, and assignment compatibility relationships as defined in the following sections.
For purposes of determining type relationships, all object types appear to have the members of the ‘Object’ interface unless those members are hidden by members with the same name in the object types, and object types with one or more call or construct signatures appear to have the members of the ‘Function’ interface unless those members are hidden by members with the same name in the object types.
For purposes of determining subtype, supertype, and assignment compatibility relationships, the Number, Boolean, and String primitive types are treated as object types with the same properties as the ‘Number’, ‘Boolean’, and ‘String’ interfaces respectively. Likewise, enum types are treated as object types with the same properties as the ‘Number’ interface.
All type parameters appear to have the members of their constraint (or the ‘Object’ interface if they have no constraint), but no other members.
Two types are considered identical when
· they are the same primitive type,
· they are the same type parameter, or
· they are object types with identical sets of members.
Two members are considered identical when
· they are public properties with identical names, optionality, and types,
· they are private properties originating in the same declaration and having identical types,
· they are identical call signatures,
· they are identical construct signatures, or
· they are index signatures of identical kind with identical types.
Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those type parameters pairwise identical, have identical type parameter constraints, identical number of parameters of identical kinds and types, and identical return types.
Note that, except for primitive types and classes with private members, it is structure, not naming, of types that determines identity. Also, note that parameter names are not significant when determining identity of signatures.
Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type
interface A { next: A; }
contains an infinitely nested sequence of ‘next’ properties. Types such as this are perfectly valid but require special treatment when determining type relationships. Specifically, when comparing references to two named types S and T for a given relationship (identity, subtype, or assignability), the relationship in question is assumed to be true for every directly or indirectly nested occurrence of references to the same S and T (where same means originating in the same declaration). For example, consider the identity relationship between ‘A’ above and ‘B’ below:
interface B { next: C; }
interface C { next: D; }
interface D { next: B; }
To determine whether ‘A’ and ‘B’ are identical, first the ‘next’ properties of type ‘A’ and ‘C’ are compared. That leads to comparing the ‘next’ properties of type ‘A’ and ‘D’, which leads to comparing the ‘next’ properties of type ‘A’ and ‘B’. Since ‘A’ and ‘B’ are already being compared this relationship is by definition true. That in turn causes the other comparisons to be true, and therefore the final result is true.
When this same technique is used to compare generic type references, two type references are considered the same when they originate in the same declaration and have identical type arguments. However, certain recursive generic patterns are prohibited, as explained in section 3.5.2.
Private properties match only if they originate in the same declaration and have identical types. Two distinct types might contain properties that originate in the same declaration if the types are separate parameterized references to the same generic class. In the example
class C<T> { private x: T; }
interface X { f(): string; }
interface Y { f(): string; }
var a: C<X>;
var b: C<Y>;
the variables ‘a’ and ‘b’ are of identical types because the two type references to ‘C’ create types with a private member ‘x’ that originates in the same declaration, and because the two private ‘x’ members have types with identical sets of members once the type arguments ‘X’ and ‘Y’ are substituted.
Given a type S and a substitution type S’ where
· when S is the primitive type Number, Boolean, or String, S’ is the global interface type ‘Number’, ‘Boolean’, or ‘String’,
· when S is an enum type, S’ is the global interface type ‘Number’,
· when S is a type parameter, S’ is the constraint of that type parameter,
· otherwise, S’ is S,
S is a subtype of a type T, and T is a supertype of S, if one of the following is true:
· S and T are identical types.
· T is the Any type.
· S is the Undefined type.
· S is the Null type and T is not the Undefined type.
· S is an enum type and T is the primitive type Number.
· S is a string literal type and T is the primitive type String.
· S and T are type parameters, and S is directly or indirectly constrained to T.
· S’ and T are object types and, for each member M in T, one of the following is true:
o M is a public property and S’ contains a public property of the same name as M and a type that is a subtype of that of M.
o M is a private property and S’ contains a private property that originates in the same declaration as M and has a type that is a subtype of that of M.
o M is an optional property and S’ contains no property of the same name as M.
o M is a non-specialized call or construct signature and S’ contains a call or construct signature N where, when substituting ‘Object’ for all type parameters declared by M and N (if any),
§ the signatures are of the same kind (call or construct),
§ the number of non-optional parameters in N is less than or equal to that of M,
§ for parameter positions that are present in both signatures, each parameter type in N is a subtype or supertype of the corresponding parameter type in M,
§ the result type of M is Void, or the result type of N is a subtype of that of M.
o M is a string index signature of type U and S’ contains a string index signature of a type that is a subtype of U.
o M is a numeric index signature of type U and S’ contains a string or numeric index signature of a type that is a subtype of U.
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
Note that specialized call and construct signatures (section 3.7.2.4) are not significant when determining subtype and supertype relationships.
Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls.
Given a type S and a substitution type S’ where
· when S is the primitive type Number, Boolean, or String, S’ is the global interface type ‘Number’, ‘Boolean’, or ‘String’,
· when S is an enum type, S’ is the global interface type ‘Number’,
· when S is a type parameter, S’ is the constraint of that type parameter,
· otherwise, S’ is S,
S is assignable to a type T, and T is assignable from S, if one of the following is true:
· S and T are identical types.
· S or T is the Any type.
· S is the Undefined type.
· S is the Null type and T is not the Undefined type.
· S or T is an enum type and the other is the primitive type Number.
· S and T are type parameters, and S is directly or indirectly constrained to T.
· S’ and T are object types and, for each member M in T, one of the following is true:
o M is a public property and S’ contains a public property of the same name as M and a type that is assignable to that of M.
o M is a private property and S’ contains a private property that originates in the same declaration as M and has a type that is assignable to that of M.
o M is an optional property and S’ contains no property of the same name as M.
o M is a non-specialized call or construct signature and S’ contains a call or construct signature N where, when substituting ‘Object’ for all type parameters declared by M and N (if any),
§ the signatures are of the same kind (call or construct),
§ the number of non-optional parameters in N is less than or equal to that of M,
§ for parameter positions that are present in both signatures, each parameter type in N is assignable to or from the corresponding parameter type in M,
§ the result type of M is Void, or the result type of N is assignable to that of M.
o M is a numeric index signature of type U and S’ contains a string or numeric index signature of a type that is assignable to U.
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
Note that specialized call and construct signatures (section 3.7.2.4) are not significant when determining assignment compatibility.
The assignment compatibility and subtyping rules differ only in that
· the Any type is assignable to, but not a subtype of, all types, and
· the primitive type Number is assignable to, but not a subtype of, all enum types.
The assignment compatibility rules imply that, when assigning values or passing parameters, optional properties must either be present and of a compatible type, or not be present at all. For example:
function foo(x: { id: number; name?: string; }) { }
foo({ id: 1234 }); //
Ok
foo({ id: 1234, name: "hello" }); // Ok
foo({ id: 1234, name: false }); // Error, name of wrong
type
foo({ name: "hello" }); // Error, id required but missing
In several situations TypeScript infers types from context, alleviating the need for the programmer to explicitly specify types that appear obvious. For example
var name = "Steve";
infers the type of ‘name’ to be the String primitive type since that is the type of the value used to initialize it. When inferring the type of a variable, property or function result from an expression, the widened form of the source type is used as the inferred type of the target. The widened form of a type is the type in which all occurrences of the Null and Undefined types have been replaced with the type any.
The following example shows the results of widening types to produce inferred variable types.
var a = null;
// var a: any
var b =
undefined; // var b:
any
var c = { x: 0, y: null }; // var c: { x: number, y: any }
var d = [ null, undefined ]; // var d: any[]
In some cases a best common type needs to be inferred from a set of types. In particular, return types of functions with multiple return statements and element types of array literals are found this way.
For an empty set of types, the best common type is the Any type.
For a non-empty set of types { T1, T2, …, Tn }, the best common type is the one Tx in the set that is a supertype of every Tn. It is possible that no such type exists, in which case the best common type is an empty object type (the type {}).
TypeScript Language Specification (converted to HTML pages by @Bartvds)
Version 0.9.1
August 2013
Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ('OWF 1.0') as of October 1, 2012. The OWF 1.0 is available at http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0.
TypeScript is a trademark of Microsoft Corporation.