Functions
Declaring a function
Every parameter has a type and every function declares what it returns:
ts
function add(a: int, b: int): int {
return a + b;
}
function log(message: string): void {
console.log("[game] " + message);
}
log("sum is " + add(2, 3));Functions declared at the top level of a file can be called from anywhere in that file, even above the declaration.
Arrow functions
ts
const square: (x: float) => float = (x: float): float => x * x;
const clamp: (v: int, lo: int, hi: int) => int = (v: int, lo: int, hi: int): int => {
if (v < lo) {
return lo;
}
if (v > hi) {
return hi;
}
return v;
};
console.log(square(3), clamp(12, 0, 10));A function type is written (x: float) => float. You can also use the plain Function type when the exact signature does not matter.
When an arrow function is passed somewhere that already has a function type, its parameter types come from there:
ts
const nums: Array<int> = [1, 2, 3, 4];
const evens: Array<int> = nums.filter((n: int): boolean => n % 2 == 0);
console.log(evens.join(","));Default parameters
ts
function greet(name: string = "world"): string {
return "Hello, " + name;
}
console.log(greet());
console.log(greet("Ada"));Rest parameters and spread
ts
function sum(...nums: Array<int>): int {
let total: int = 0;
for (const n of nums) {
total += n;
}
return total;
}
const values: Array<int> = [4, 5, 6];
console.log(sum(1, 2, 3));
console.log(sum(...values));Every argument a rest parameter collects is checked against its element type.
Closures
A function keeps access to the variables around it, even after the outer function returns:
ts
function makeCounter(): () => int {
let count: int = 0;
return (): int => {
count += 1;
return count;
};
}
const next: () => int = makeCounter();
console.log(next()); // 1
console.log(next()); // 2Functions are values
Pass them in, return them, store them:
ts
function applyTwice(f: (n: int) => int, x: int): int {
return f(f(x));
}
const double: (n: int) => int = (n: int): int => n * 2;
console.log(applyTwice(double, 3)); // 12Async functions
An async function returns a Promise and can use await. See Async, series and parallel.