this
as a parameter (advanced)This chapter explores static typing for functions in TypeScript.
in this chapter, “function” means “function or method or constructor”
In this chapter, most things that are said about functions (especially w.r.t. parameter handling), also apply to methods and constructors.
This is an example of a function declaration in TypeScript:
function repeat1(str: string, times: number): string { // (A)
.repeat(times);
return str
}.equal(
assertrepeat1('*', 5), '*****');
Parameters: If the compiler option --noImplicitAny
is on (which it is if --strict
is on), then the type of each parameter must be either inferrable or explicitly specified. (We’ll take a closer look at inference later.) In this case, no inference is possible, which is why str
and times
have type annotations.
Return value: By default, the return type of functions is inferred. That is usually good enough. In this case, we opted to explicitly specify that repeat1()
has the return type string
(last type annotation in line A).
The arrow function version of repeat1()
looks as follows:
= (str: string, times: number): string => {
const repeat2 .repeat(times);
return str; }
In this case, we can also use an expression body:
= (str: string, times: number): string =>
const repeat3 .repeat(times); str
We can define types for functions via function type signatures:
type Repeat = (str: string, times: number) => string;
The name of this type of function is Repeat
. Among others, it matches all functions with:
string
and number
. We need to name parameters in function type signatures, but the names are ignored when checking if two function types are compatible.string
. Note that this time, the type is separated by an arrow and can’t be omitted.This type matches more functions. We’ll learn which ones, when we explore the rules for assignability later in this chapter.
We can also use interfaces to define function types:
interface Repeat {: string, times: number): string; // (A)
(str }
Note:
On one hand, interfaces are more verbose. On the other hand, they let us specify properties of functions (which is rare, but does happen):
interface Incrementor1 {: number): number;
(x: number;
increment }
We can also specify properties via an intersection type (&
) of a function signature type and an object literal type:
type Incrementor2 =
: number) => number
(x& { increment: number }
;
As an example, consider this scenario: A library exports the following function type.
type StringPredicate = (str: string) => boolean;
We want to define a function whose type is compatible with StringPredicate
. And we want to check immediately if that’s indeed the case (vs. finding out later when we use it for the first time).
If we declare a variable via const
, we can perform the check via a type annotation:
: StringPredicate = (str) => str.length > 0; const pred1
Note that we don’t need to specify the type of parameter str
because TypeScript can use StringPredicate
to infer it.
Checking function declarations is more complicated:
function pred2(str: string): boolean {
.length > 0;
return str
}
// Assign the function to a type-annotated variable
: StringPredicate = pred2; const pred2ImplementsStringPredicate
The following solution is slightly over the top (i.e., don’t worry if you don’t fully understand it), but it demonstrates several advanced features:
function pred3(...[str]: Parameters<StringPredicate>)
: ReturnType<StringPredicate> {
.length > 0;
return str }
Parameters: We use Parameters<>
to extract a tuple with the parameter types. The three dots declare a rest parameter, which collects all parameters in a tuple/Array. [str]
destructures that tuple. (More on rest parameters later in this chapter.)
Return value: We use ReturnType<>
to extract the return type.
Recap: If --noImplicitAny
is switched on (--strict
switches it on), the type of each parameter must either be inferrable or explicitly specified.
In the following example, TypeScript can’t infer the type of str
and we must specify it:
function twice(str: string) {
+ str;
return str }
In line A, TypeScript can use the type StringMapFunction
to infer the type of str
and we don’t need to add a type annotation:
type StringMapFunction = (str: string) => string;
: StringMapFunction = (str) => str + str; // (A) const twice
Here, TypeScript can use the type of .map()
to infer the type of str
:
.deepEqual(
assert'a', 'b', 'c'].map((str) => str + str),
['aa', 'bb', 'cc']); [
This is the type of .map()
:
<T> {
interface Arraymap<U>(
: (value: T, index: number, array: T[]) => U,
callbackfn?: any
thisArg: U[];
)// ···
}
In this section, we look at several ways in which we can allow parameters to be omitted.
str?: string
If we put a question mark after the name of a parameter, that parameter becomes optional and can be omitted when calling the function:
function trim1(str?: string): string {
// Internal type of str:
// %inferred-type: string | undefined
;
str
if (str === undefined) {
'';
return
}.trim();
return str
}
// External type of trim1:
// %inferred-type: (str?: string | undefined) => string
; trim1
This is how trim1()
can be invoked:
.equal(
asserttrim1('\n abc \t'), 'abc');
.equal(
asserttrim1(), '');
// `undefined` is equivalent to omitting the parameter
.equal(
asserttrim1(undefined), '');
str: undefined|string
Externally, parameter str
of trim1()
has the type string|undefined
. Therefore, trim1()
is mostly equivalent to the following function.
function trim2(str: undefined|string): string {
// Internal type of str:
// %inferred-type: string | undefined
;
str
if (str === undefined) {
'';
return
}.trim();
return str
}
// External type of trim2:
// %inferred-type: (str: string | undefined) => string
; trim2
The only way in which trim2()
is different from trim1()
is that the parameter can’t be omitted in function calls (line A). In other words: We must be explicit when omitting a parameter whose type is undefined|T
.
.equal(
asserttrim2('\n abc \t'), 'abc');
// @ts-expect-error: Expected 1 arguments, but got 0. (2554)
trim2(); // (A)
.equal(
asserttrim2(undefined), ''); // OK!
str = ''
If we specify a parameter default value for str
, we don’t need to provide a type annotation because TypeScript can infer the type:
function trim3(str = ''): string {
// Internal type of str:
// %inferred-type: string
;
str
.trim();
return str
}
// External type of trim2:
// %inferred-type: (str?: string) => string
; trim3
Note that the internal type of str
is string
because the default value ensures that it is never undefined
.
Let’s invoke trim3()
:
.equal(
asserttrim3('\n abc \t'), 'abc');
// Omitting the parameter triggers the parameter default value:
.equal(
asserttrim3(), '');
// `undefined` is allowed and triggers the parameter default value:
.equal(
asserttrim3(undefined), '');
We can also specify both a type and a default value:
function trim4(str: string = ''): string {
.trim();
return str }
A rest parameter collects all remaining parameters in an Array. Therefore, its static type is usually an Array. In the following example, parts
is a rest parameter:
function join(separator: string, ...parts: string[]) {
.join(separator);
return parts
}.equal(
assertjoin('-', 'state', 'of', 'the', 'art'),
'state-of-the-art');
The next example demonstrates two features:
[string, number]
for rest parameters.function repeat1(...[str, times]: [string, number]): string {
.repeat(times);
return str }
repeat1()
is equivalent to the following function:
function repeat2(str: string, times: number): string {
.repeat(times);
return str }
Named parameters are a popular pattern in JavaScript where an object literal is used to give each parameter a name. That looks as follows:
.equal(
assertpadStart({str: '7', len: 3, fillStr: '0'}),
'007');
In plain JavaScript, functions can use destructuring to access named parameter values. Alas, in TypeScript, we additionally have to specify a type for the object literal and that leads to redundancies:
function padStart({ str, len, fillStr = ' ' } // (A)
: { str: string, len: number, fillStr: string }) { // (B)
.padStart(len, fillStr);
return str }
Note that the destructuring (incl. the default value for fillStr
) all happens in line A, while line B is exclusively about TypeScript.
It is possible to define a separate type instead of the inlined object literal type that we have used in line B. However, in most cases, I prefer not to do that because it slightly goes against the nature of parameters which are local and unique per function. If you prefer having less stuff in function heads, then that’s OK, too.
this
as a parameter (advanced)Each ordinary function always has the implicit parameter this
– which enables it to be used as a method in objects. Sometimes we need to specify a type for this
. There is TypeScript-only syntax for this use case: One of the parameters of an ordinary function can have the name this
. Such a parameter only exists at compile time and disappears at runtime.
As an example, consider the following interface for DOM event sources (in a slightly simplified version):
interface EventSource {addEventListener(
: string,
type: (this: EventSource, ev: Event) => any,
listener?: boolean | AddEventListenerOptions
options: void;
)// ···
}
The this
of the callback listener
is always an instance of EventSource
.
The next example demonstrates that TypeScript uses the type information provided by the this
parameter to check the first argument of .call()
(line A and line B):
function toIsoString(this: Date): string {
.toISOString();
return this
}
// @ts-expect-error: Argument of type '"abc"' is not assignable to
// parameter of type 'Date'. (2345)
.throws(() => toIsoString.call('abc')); // (A) error
assert
.call(new Date()); // (B) OK toIsoString
Additionally, we can’t invoke toIsoString()
as a method of an object obj
because then its receiver isn’t an instance of Date
:
= { toIsoString };
const obj // @ts-expect-error: The 'this' context of type
// '{ toIsoString: (this: Date) => string; }' is not assignable to
// method's 'this' of type 'Date'. [...]
.throws(() => obj.toIsoString()); // error
assert.toIsoString.call(new Date()); // OK obj
Sometimes a single type signature does not adequately describe how a function works.
Consider function getFullName()
which we are calling in the following example (line A and line B):
interface Customer {: string;
id: string;
fullName
}= {id: '1234', fullName: 'Jane Bond'};
const jane = {id: '5678', fullName: 'Lars Croft'};
const lars = new Map<string, Customer>([
const idToCustomer '1234', jane],
['5678', lars],
[;
])
.equal(
assertgetFullName(idToCustomer, '1234'), 'Jane Bond'); // (A)
.equal(
assertgetFullName(lars), 'Lars Croft'); // (B)
How would we implement getFullName()
? The following implementation works for the two function calls in the previous example:
function getFullName(
: Customer | Map<string, Customer>,
customerOrMap?: string
id: string {
)if (customerOrMap instanceof Map) {
if (id === undefined) throw new Error();
= customerOrMap.get(id);
const customer if (customer === undefined) {
new Error('Unknown ID: ' + id);
throw
}= customer;
customerOrMap
} else {if (id !== undefined) throw new Error();
}.fullName;
return customerOrMap }
However, with this type signature, function calls are legal at compile time that produce runtime errors:
.throws(() => getFullName(idToCustomer)); // missing ID
assert.throws(() => getFullName(lars, '5678')); // ID not allowed assert
The following code fixes these issues:
function getFullName(customerOrMap: Customer): string; // (A)
function getFullName( // (B)
: Map<string, Customer>, id: string): string;
customerOrMapfunction getFullName( // (C)
: Customer | Map<string, Customer>,
customerOrMap?: string
id: string {
)// ···
}
// @ts-expect-error: Argument of type 'Map<string, Customer>' is not
// assignable to parameter of type 'Customer'. [...]
getFullName(idToCustomer); // missing ID
// @ts-expect-error: Argument of type '{ id: string; fullName: string; }'
// is not assignable to parameter of type 'Map<string, Customer>'.
// [...]
getFullName(lars, '5678'); // ID not allowed
What is going on here? The type signature of getFullName()
is overloaded:
getFullName()
. The type signature of the actual implementation cannot be used!My advice is to only use overloading when it can’t be avoided. One alternative is to split an overloaded function into multiple functions with different names – for example:
getFullName()
getFullNameViaMap()
In interfaces, we can have multiple, different call signatures. That enables us to use the interface GetFullName
for overloading in the following example:
interface GetFullName {: Customer): string;
(customerOrMap: Map<string, Customer>, id: string): string;
(customerOrMap
}
: GetFullName = (
const getFullName: Customer | Map<string, Customer>,
customerOrMap?: string
id: string => {
)if (customerOrMap instanceof Map) {
if (id === undefined) throw new Error();
= customerOrMap.get(id);
const customer if (customer === undefined) {
new Error('Unknown ID: ' + id);
throw
}= customer;
customerOrMap
} else {if (id !== undefined) throw new Error();
}.fullName;
return customerOrMap }
In the next example, we overload and use string literal types (such as 'click'
). That allows us to change the type of parameter listener
depending on the value of parameter type
:
function addEventListener(elem: HTMLElement, type: 'click',
: (event: MouseEvent) => void): void;
listenerfunction addEventListener(elem: HTMLElement, type: 'keypress',
: (event: KeyboardEvent) => void): void;
listenerfunction addEventListener(elem: HTMLElement, type: string, // (A)
: (event: any) => void): void {
listener.addEventListener(type, listener); // (B)
elem }
In this case, it is relatively difficult to get the types of the implementation (starting in line A) right, so that the statement in the body (line B) works. As a last resort, we can always use the type any
.
The next example demonstrates overloading of methods: Method .add()
is overloaded.
class StringBuilder {= '';
#data
add(num: number): this;
add(bool: boolean): this;
add(str: string): this;
add(value: any): this {
.#data += String(value);
this;
return this
}
toString() {
.#data;
return this
}
}
= new StringBuilder();
const sb
sb.add('I can see ')
.add(3)
.add(' monkeys!')
;
.equal(
assert.toString(), 'I can see 3 monkeys!') sb
The type definition for Array.from()
is an example of an overloaded interface method:
interface ArrayConstructor {from<T>(arrayLike: ArrayLike<T>): T[];
from<T, U>(
: ArrayLike<T>,
arrayLike: (v: T, k: number) => U,
mapfn?: any
thisArg: U[];
) }
In the first signature, the returned Array has the same element type as the parameter.
In the second signature, the elements of the returned Array have the same type as the result of mapfn
. This version of Array.from()
is similar to Array.prototype.map()
.
In this section we look at the type compatibility rules for assignability: Can functions of type Src
be transferred to storage locations (variables, object properties, parameters, etc.) of type Trg
?
Understanding assignability helps us answer questions such as:
In this subsection, we examine general rules for assignability (including the rules for functions). In the next subsection, we explore what those rules mean for functions.
A type Src
is assignable to a type Trg
if one of the following conditions is true:
Src
and Trg
are identical types.Src
or Trg
is the any
type.Src
is a string literal type and Trg
is the primitive type String.Src
is a union type and each constituent type of Src
is assignable to Trg
.Src
and Trg
are function types and:
Trg
has a rest parameter or the number of required parameters of Src
is less than or equal to the total number of parameters of Trg
.Trg
is assignable to the corresponding parameter type in Src
.Trg
is void
or the return type of Src
is assignable to the return type of Trg
.In this subsection, we look at what the assignment rules mean for the following two functions targetFunc
and sourceFunc
:
: Trg = sourceFunc; const targetFunc
Example:
: (x: RegExp) => Object = (x: Object) => /abc/; const trg1
The following example demonstrates that if the target return type is void
, then the source return type doesn’t matter. Why is that? void
results are always ignored in TypeScript.
: () => void = () => new Date(); const trg2
The source must not have more parameters than the target:
// @ts-expect-error: Type '(x: string) => string' is not assignable to
// type '() => string'. (2322)
: () => string = (x: string) => 'abc'; const trg3
The source can have fewer parameters than the target:
: (x: string) => string = () => 'abc'; const trg4
Why is that? The target specifies the expectations for the source: It must accept the parameter x
. Which it does (but it ignores it). This permissiveness enables:
'a', 'b'].map(x => x + x) [
The callback for .map()
only has one of the three parameters that are mentioned in the type signature of .map()
:
map<U>(
: (value: T, index: number, array: T[]) => U,
callback?: any
thisArg: U[]; )