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, and is assignable to and from 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. An object type can have at most one string index signature and one numeric index signature.
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.4.
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.
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.
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 Constraint(opt)
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, with the exception of static member declarations in classes.
Each type parameter has an associated type parameter constraint that establishes an upper bound for type arguments. Omitting a constraint corresponds to specifying the empty object type {}. Type parameters declared in a particular type parameter list may not be referenced in constraints in that type parameter list.
The base constraint of a type parameter T is defined as follows:
- If T has no declared constraint, T's base constraint is the empty object type {}.
- If T's declared constraint is a type parameter, T's base constraint is that of the type parameter.
- Otherwise, T's base constraint is T's declared constraint.
In the example
interface G<T, U extends Function> {
f<V extends U>(x: V): V;
}
the base constraint of T
is the empty object type, and the base constraint of U
and V
is Function
.
For purposes of determining type relationships (section 3.8), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section 4.10), new operations (section 4.11), and function calls (section 4.12), type parameters appear to have the members of their base constraint, but no other members.
A type reference (section 3.6.2) to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas. Similarly, a call (section 4.12) to a generic function may explicitly include a type argument list instead of relying on type inference.
TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument
TypeArgumentList , TypeArgument
TypeArgument:
Type
Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument is required to satisfy the constraint of its corresponding type
parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section 3.8.4) the constraint type once type arguments are substituted for type parameters.
Given the declaration
interface G<T, U extends Function> { }
a type reference of the form G<A, B>
places no requirements on A
but requires B
to be assignable to
Function
.
The process of substituting type arguments for type parameters in a generic type or generic signature is known as instantiating the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters.
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. This substitution process is known as instantiating a generic type. Only once a generic type is instantiated does it denote an actual type.
TypeScript has a structural type system, and therefore an instantiation of 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; }
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 an instantiation of the generic type where each of the 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 instance 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 [no LineTerminator here] TypeArguments(opt)
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 (section 3.4.2).
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 is required to specify exactly one type argument for each type parameter of the referenced generic type, and each type argument must be assignable to (section 3.8.4) 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.
As described in section 3.5, 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 widened type (section
3.9) 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:
ElementType [no LineTerminator here] [ ]
ElementType:
PredefinedType
TypeReference
TypeQuery
ObjectType
ArrayType
FunctionType:
TypeParameters(opt) ( ParameterList(opt) ) => Type
ConstructorType:
new TypeParameters(opt) ( ParameterList(opt) ) => 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 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:
{ TypeBody(opt) }
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) TypeAnnotation(opt)
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:
TypeParameters(opt) ( ParameterList(opt) ) TypeAnnotation(opt)
A call signature that includes TypeParameters (section 3.4.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.
Type parameters (section 3.4.1) 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.
Type parameters may be referenced in parameter types and return type annotations, but not in type parameter constraints, of the call signature in which they are introduced.
Type arguments (section 3.4.2) 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. An instantiation of a generic call signature for a particular set of type arguments is the call signature formed by replacing each type parameter with its corresponding type argument.
Some examples of call signatures with type parameters:
Type parameter | Description |
---|---|
(x: T): T | A function taking an argument of any type, returning a value of that same type. |
(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:
PublicOrPrivate(opt) Identifier TypeAnnotation(opt)
Identifier : StringLiteral
PublicOrPrivate:
public
private
OptionalParameterList:
OptionalParameter
OptionalParameterList , OptionalParameter
OptionalParameter:
PublicOrPrivate(opt) Identifier ? TypeAnnotation(opt)
PublicOrPrivate(opt) Identifier TypeAnnotation(opt) Initialiser
RestParameter:
... Identifier TypeAnnotation(opt)
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.
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: "div"): HTMLDivElement;
createElement(tagName: "span"): HTMLSpanElement;
createElement(tagName: "canvas"): HTMLCanvasElement;
createElement(tagName: string): HTMLElement;
}
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
.
When writing overloaded declarations such as the one above it is important to list the non-specialized signature last. This is because overload resolution (section 4.12.1) processes the candidates in declaration order and picks the first one that matches.
Every specialized call or construct signature in an object type must be assignable to at least one non-
specialized call or construct signature in the same object type (where a call signature A is considered
assignable to another call signature B if an object type containing only A would be assignable to an object
type containing only B). For example, the createElement
property in the example above is of a type that
contains three specialized signatures, all of which are assignable to 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 TypeParameters(opt) ( ParameterList(opt) ) TypeAnnotation(opt)
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.
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 assignable to 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 assignable to 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.
An object type can contain at most one string index signature and one numeric index signature.
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. Apparent types (section 3.8.1) that are object types appear to have these extra members as well.
In certain contexts a type appears to have the characteristics of a related type called the type's apparent type. Specifically, a type's apparent type is used when determining subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section 4.10), new operations (section 4.11), and function calls (section 4.12).
The apparent type of a type T is defined as follows:
- If T is the primitive type Number, Boolean, or String, the apparent type of T is the augmented
form (as defined below) of the global interface type
Number
,Boolean
, orString
. - if T is an enum type, the apparent type of T is the augmented form of the global interface type
Number
. - If T is an object type, the apparent type of T is the augmented form of T.
- If T is a type parameter, the apparent type of T is the apparent type of T's base constraint (section 3.4.1).
- Otherwise, the apparent type of T is T itself.
The augmented form of an object type T adds to T those members of the global interface type Object
that aren't hidden by members in T. Furthermore, if T has one or more call or construct signatures, the
augmented form of T adds to T the members of the global interface type Function
that aren't hidden by
members in T. Members in T hide Object
or Function
interface members in the following manner:
- A property hides an
Object
orFunction
property with the same name. - A call signature hides an
Object
orFunction
call signature with the same number of parameters and identical parameter types in the respective positions. - A construct signature hides an
Object
orFunction
construct signature with the same number of parameters and identical parameter types in the respective positions. - An index signature hides an
Object
orFunction
index signature with the same parameter type.
In effect, a type's apparent type is a subtype of the Object
or Function
interface unless the type defines
members that are incompatible with those of the Object
or Function
interface—which, for example,
occurs if the 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
The last assignment is an error because the apparent type of the object literal has a toString
method that
isn't compatible with that of Object
.
Two types are considered identical when
- they are both the Any type,
- 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 with identical type parameter constraints and, after substituting type Any for the type parameters introduced by the signatures, identical number of parameters with identical kind (required, optional or rest) 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.
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.
S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S:
- 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:
- M is a property and S' contains a property N where
- M and N have the same name,
- the type of N is a subtype of that of M,
- M and N are both public, or M and N are both private and originate in the same declaration, and
- if M is a required property, N is also a required property.
- M is an optional property and S' contains no property of the same name as M.
- M is a non-specialized call or construct signature and S' contains a call or construct
signature N where, when M and N are instantiated using type Any as the type argument
for all type parameters declared by M and N (if any),
- the signatures are of the same kind (call or construct),
- M has a rest parameter or the number of non-optional parameters in N is less than or equal to the total number of parameters in 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, and
- the result type of M is Void, or the result type of N is a subtype of that of M.
- 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.
- 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.
- M is a property and S' contains a property N where
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.
Also note that type parameters are not considered object types. Thus, the only subtypes of a type parameter T are T itself and other type parameters that are directly or indirectly constrained to T.
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.
S is assignable to a type T, and T is assignable from S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S:
- 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 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:
- M is a property and S' contains a property N where
- M and N have the same name,
- the type of N is assignable to that of M,
- M and N are both public, or M and N are both private and originate in the same declaration, and
- if M is a required property, N is also a required property.
- M is an optional property and S' contains no property of the same name as M.
- M is a non-specialized call or construct signature and S' contains a call or construct
signature N where, when M and N are instantiated using type Any as the type argument
for all type parameters declared by M and N (if any),
- the signatures are of the same kind (call or construct),
- M has a rest parameter or the number of non-optional parameters in N is less than or equal to the total number of parameters in 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, and
- the result type of M is Void, or the result type of N is assignable to that of M.
- M is a string index signature of type U and S' contains a string index signature of a type that is assignable to U.
- 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.
- M is a property and S' contains a property N where
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
During type argument inference in a function call (section 4.12.2) it is in certain circumstances necessary to instantiate a generic call signature of an argument expression in the context of a non-generic call signature of a parameter such that further inferences can be made. A generic call signature A is instantiated in the context of non-generic call signature B as follows:
- Using the process described in 3.8.6, inferences for A's type parameters are made from each parameter type in B to the corresponding parameter type in A for those parameter positions that are present in both signatures, where rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
- The inferred type argument for each type parameter is the best common type (section 3.10) of the set of inferences made for that type parameter. However, if the best common type does not satisfy the constraint of the type parameter, the inferred type argument is instead the constraint.
In certain contexts, inferences for a given set of type parameters are made from a type S, in which those type parameters do not occur, to another type T, in which those type parameters do occur. Inferences consist of a set of candidate type arguments collected for each of the type parameters. The inference process recursively relates S and T to gather as many inferences as possible:
- If T is one of the type parameters for which inferences are being made, S is added to the set of inferences for that type parameter.
- Otherwise, if S and T are object types, then for each member M in T:
- If M is a property and S contains a property N with the same name as M, inferences are made from the type of N to the type of M.
- If M is a call signature then for each call signature N in S, N is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in N to the corresponding parameter types in M for positions that are present in both signatures, and from the return type of N to the return type of M.
- If M is a construct signature then for each construct signature N in S, N is instantiated with the Any type as an argument for each type parameter (if any) and inferences are made from parameter types in N to the corresponding parameter types in M for positions that are present in both signatures, and from the return type of N to the return type of M.
- If M is a string index signature and S contains a string index signature N, inferences are made from the type of N to the type of M.
- If M is a numeric index signature and S contains a numeric index signature N, inferences are made from the type of N to the type of M.
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 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 the same S and the same T (where same means
originating in the same declaration and, if applicable, having identical type arguments). 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.
In certain circumstances, generic types that directly or indirectly reference themselves in a recursive fashion can lead to infinite series of distinct instantiations. For example, in the type
interface List<T> {
data: T;
next: List<T>;
owner: List<List<T>>;
}
List<T>
has a member owner
of type List<List<T>>
, which has a member owner
of type
List<List<List<T>>>
, which has a member owner
of type List<List<List<List<T>>>>
and so on, ad
infinitum. Since type relationships are determined structurally, possibly exploring the constituent types to
their full depth, in order to determine type relationships involving infinitely expanding generic types it is
necessary to introduce a mechanism that terminates the recursion.
Within a generic class or interface G, type references contained in declared or inherited members are classified as follows
- A type reference without type arguments or with type arguments that do not reference any of G's type parameters is classified as a closed type reference.
- A type reference that references any of G's type parameters in a type argument is classified as an open type reference.
- A type reference which, directly or indirectly, references G through open type references and which contains a wrapped form of any of G's type parameters in one or more type arguments is classified as an infinitely expanding type reference. A type is said to wrap a type parameter if it references the type parameter but isn't simply the type parameter itself.
A type is said to originate in an infinitely expanding type reference if it was created (by instantiation of a generic class or interface) from an infinitely expanding type reference (in that generic class or interface).
When comparing two types S and T for identity (section 3.8.2), subtype (section 3.8.3), and assignability (section 3.8.4) relationships, if either type originates in an infinitely expanding type reference and the other is not the Any, Null, or Undefined type, S and T are not compared by the rules in the preceding sections. Instead, for the relationship to be considered true,
- S and T must both be type references to the same named type, and
- the relationship in question must be true for each corresponding pair of type arguments in the type argument lists of S and T.
Likewise, when making type inferences (section 3.8.6) from a type S to a type T, if either type originates in an infinitely expanding type reference, then
- if S and T are type references to the same named type, inferences are made from each type argument in S to each type argument in T,
- otherwise, no inferences are made.
Referring to the example above, the List<T>
type reference in the next
property is classified as an open
type reference and the List<List<T>>
type reference in the owner
property is classified as an infinitely
expanding type reference.
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 an empty object type (the 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 or more than one such type exists, in which case the best common type is an empty object type.