Functions
A Nish function is an arrow bound to a top-level const, with every
parameter and its return type written out. The normative rules are in the
reference's Functions,
main and
Function parameters sections.
Declaring a function
const add = (a: i32, b: i32): i32 => {
return a + b;
};
const double = (n: i32): i32 => n * 2; // a concise body is one `return`
const greet = (name: string): void => {
console.log(`hello, ${name}`);
};
export const main = (): i32 => {
greet("nish"); // hello, nish
console.log(`${double(add(2, 3))}`); // 10
return 0;
};
- Annotate every parameter and the return type. A function's signature is never inferred from its body.
-
Functions live at the top level. A function declared inside another
one is refused; so is a
letbound to an arrow. - Order does not matter. A top-level function is in scope for the whole file, so two functions may call each other whichever is written first.
-
A call passes every argument it has no default for, each of exactly
the parameter's type. See Default and rest
parameters; optional (
n?: i32) and destructured parameters are not supported: take the value, then destructure it in the body. -
A non-
voidfunction returns on every path, or ends inpanic(message)orprocess.exit(code).
The function keyword is accepted too, and compiles to exactly the same
thing; the arrow is the house style.
Default and rest parameters
A trailing parameter may have a default, which a call that leaves it out
passes. A default is a constant — a number, true/false, a string, an enum
member — or the name of an earlier parameter, and the parameter keeps its type
annotation:
const scale = (x: i32, by: i32 = 2): i32 => x * by;
const area = (w: i32, h: i32 = w): i32 => w * h;
export const main = (): i32 => {
console.log(`${scale(3)} ${scale(3, 5)}`); // 6 15
console.log(`${area(4)} ${area(4, 2)}`); // 16 8
return 0;
};
The last parameter may instead be a rest parameter, an array that gathers every remaining argument. A call with none passes an empty array:
const total = (...xs: i32[]): i32 => {
let sum = 0;
for (const x of xs) {
sum += x;
}
return sum;
};
export const main = (): i32 => {
console.log(`${total()} ${total(1, 2, 3)}`); // 0 6
return 0;
};
A parameter that may be null (T | null) may default to null, and to
nothing else. That is how an options argument is written: the call that leaves
it out passes null, exactly as if it had written it:
class Options {
loud: boolean = true;
}
const greet = (name: string, opts: Options | null = null): string => {
if (opts !== null && opts.loud) {
return `${name}!`;
}
return name;
};
export const main = (): i32 => {
console.log(`${greet("a")} ${greet("b", new Options())}`); // a b!
return 0;
};
The call site fills in a default, a null default and a rest array alike, so
a function with any of them costs nothing when it is given every argument.
Methods and constructors take them too. A function
has a default or a rest parameter, not both.
A rest parameter of records copies each record into its array, as [p, q]
does, so it takes only fresh object literals: given a named record, the
callee's write would not reach it as it does in TypeScript. Pass [p, q] to a
parameter of array type instead, where the copy is written out. A class
instance is the caller's object, so a rest of class instances takes any:
interface Cell {
v: i32;
}
const bumpAll = (...cs: Cell[]): void => {
for (const c of cs) {
c.v = c.v + 100;
}
};
export const main = (): void => {
const p: Cell = { v: 1 };
bumpAll(p);
};
Optional parameters (n?: i32) are refused; write a default instead:
const greet = (name?: string): string => "hi";
A call never spreads an array into arguments; pass the array to a parameter of array type:
const xs: i32[] = [1, 2];
console.log(`${Math.max(...xs)}`);
Parameters are read-only
Assigning to a parameter is an error. Copy it into a let when you need a
value that changes:
const countdown = (n: i32): i32 => {
n = n - 1;
return n;
};
const countdown = (n: i32): i32 => {
let left = n;
while (left > 0) {
left--;
}
return left;
};
main
A program starts at export const main in the file you compile. It takes no
parameters and returns either void (exit status 0) or an i32, which is
the process's exit status:
export const main = (): i32 => {
if (process.argv.length < 2) {
console.error("usage: greet <name>");
return 2;
}
console.log(`hello, ${process.argv[1]}`);
return 0;
};
The command line is process.argv, a read-only string[]. Its first
element is the program's own path, so the first argument you pass is
process.argv[1] — one index earlier than under Node, where argv[0] is
node itself.
Two other shapes start a program. An entry file with no main may write its
statements at the top level, like a script, and they run as main
(Your first program). And
main may be async, so it can await the functions it calls
(Async functions).
Passing a function to a function
A top-level function can be kept in a variable, a field or an array, and
returned, as a function reference. When a function
only needs to call the one it is given, give it a parameter of function
type written out in its parameter list instead, and pass it a named
top-level function, an arrow written right at the call, or a variable that
holds a function reference.
A field or element is refused (NL2759): read it into a const first, as in
const op = ops[0], and pass the const:
const countWhere = (xs: i32[], keep: (x: i32) => boolean): i32 => {
let n = 0;
for (const x of xs) {
if (keep(x)) {
n++;
}
}
return n;
};
const isEven = (x: i32): boolean => x % 2 === 0;
export const main = (): i32 => {
const xs = [1, 2, 3, 4, 5, 6];
console.log(`${countWhere(xs, isEven)}`); // 3
console.log(`${countWhere(xs, (x) => x > 4)}`); // 2
return 0;
};
The compiler resolves each such argument when it compiles the call and makes
a copy of countWhere that calls it directly, so there is no function
pointer and nothing to allocate at run time. That decides the rules:
-
The parameter can only be called, or passed on to another function
parameter. It is not a value, so storing, returning or comparing it is
NL2334; type the parameter through an alias (type F = (x: i32) => i32, thenf: F) when you need a function reference. -
An arrow may read the
constlocals and the parameters of the function it is written in. The compiler hands each one to the copy as one more argument, so it is still a direct call with nothing allocated. A captured array or object may be written through (hits.push(x)), because the arrow runs during the call, on the same thread:
const each = (xs: i32[], f: (x: i32) => void): void => {
for (const x of xs) {
f(x);
}
};
export const main = (): i32 => {
const limit = 3;
const hits: i32[] = [];
each([1, 5, 2, 7], (x) => {
if (x > limit) {
hits.push(x);
}
});
console.log(`${hits.length}`); // 2
return 0;
};
-
What it captures is read, never reassigned, and it may not read a
let, which could change before the arrow runs; bind it to aconstfirst (nish --fixdoes). It may not readthis(bindconst self = this), or the function's own function parameters. An arrow inside another arrow reads only its own parameters, and an arrow given to a method or a constructor, or toexpose, captures nothing. The exception is the callback of an array method,xs.sort(cmp),xs.map(f),xs.filter(f),xs.some(f),xs.every(f)orxs.findIndex(f), which captures as an arrow argument does (Sorting,map,filterandslice):
const apply = (f: (x: i32) => i32, x: i32): i32 => f(x);
export const main = (): i32 => {
let k = 3;
k = k + 1;
return apply((x) => x + k, 1);
};
- The argument's type must match exactly, parameter for parameter and the return type too.
Arrays' own map, filter, some, every, findIndex and forEach take a
callback under this same rule, one or two parameters long ((x) or
(x, i)); see Arrays and strings. Combined with type
parameters, it is also how you write what they lack, such as a fold — see
Generics.

