Functions
Relay reads a dozen environment variables, so the reading moves into helpers. A helper is only
useful if its type is as precise as the call: readEnv(env, "PORT", 8080) should give a
number, and readEnv(env, "HOST") should admit that it may be undefined. This lesson covers
the tools for that.
Parameters and return types
Section titled “Parameters and return types”Parameters always need a type unless one is inferred from context. The return type is inferred, but write it on exported functions. It documents the contract, and a mistake in the body is reported in the body instead of at every caller.
export function parsePort(raw: string): number { return Number(raw)}
// Optional and default parametersfunction connect(host: string, port?: number) { return `${host}:${port ?? 6379}`}function connectWithDefault(host: string, port = 6379) { return `${host}:${port}` // port is number}
connect("localhost")connectWithDefault("localhost", 6380)Function types
Section titled “Function types”A function’s type is written like an arrow: (line: string) => void. Use it for callbacks and
for values that hold functions.
type Write = (line: string) => void
const stdout: Write = (line) => console.log(line) // line is inferred as stringconst lines: string[] = []const memory: Write = (line) => lines.push(line) // returns a number, still fine as voidA void return in a function type means “the caller ignores the result”. That’s why
lines.push, which returns a number, is accepted. In a function declaration, void means it
returns nothing.
Rest parameters
Section titled “Rest parameters”...names: string[] collects any number of trailing arguments into an array:
function requireEnv(env: Record<string, string | undefined>, ...names: string[]): string[] { return names.map((name) => env[name] ?? "")}
requireEnv({}, "QUEUE_URL", "TOKEN")
const names = ["A", "B"]requireEnv({}, ...names) // spread an array into a rest parameterOverloads
Section titled “Overloads”Sometimes the return type depends on which arguments were passed. Overloads list each call shape with its own return type, followed by one implementation that handles them all:
type Env = Record<string, string | undefined>
function readEnv(env: Env, name: string): string | undefinedfunction readEnv(env: Env, name: string, fallback: string): stringfunction readEnv(env: Env, name: string, fallback: number): numberfunction readEnv(env: Env, name: string, fallback?: string | number): string | number | undefined { const raw = env[name] if (raw === undefined) return fallback return typeof fallback === "number" ? Number(raw) : raw}
const env: Env = {}const host = readEnv(env, "HOST") // string | undefinedconst port = readEnv(env, "PORT", 8080) // number
// @ts-expect-error: no overload accepts a boolean fallbackreadEnv(env, "DEBUG", true)- Callers see only the overloads. The implementation signature is hidden.
- The compiler checks that each overload is compatible with the implementation, but it doesn’t
check that the body returns a
numberwhen anumberfallback was passed. That part is on you, and on the tests. - Overloads are tried from top to bottom, so put the most specific ones first.
In a method, this is whatever object the method was called on. Take the method off its object,
for example by passing it as a callback, and this is lost. Declare a this parameter (it isn’t
a real argument and is erased at runtime) and the compiler catches it:
class Logger { prefix = "[relay]" log(this: Logger, line: string) { console.log(this.prefix, line) } // An arrow function property captures `this` when the object is created logBound = (line: string) => console.log(this.prefix, line)}
const logger = new Logger()const log = logger.log// @ts-expect-error: the 'this' context of type 'void' is not assignable to type 'Logger'log("boot")
;["boot", "ready"].forEach(logger.logBound) // fineExercise
Section titled “Exercise”Give readEnv overloads so each call gets its exact return type (the hidden tests check all
three), validate the number case, and make requireEnv take a rest parameter and report every
missing variable at once. One error that names everything saves several restart cycles.
- Annotate parameters always, and return types on exported functions.
(x: A) => Bis a function type. Avoidreturn in a function type means “result ignored”....rest: T[]collects arguments....arrayspreads them back.- Overloads give each call shape its own return type. The body isn’t checked against them, so test it.
- A
this: Tparameter catches methods detached from their object.
Further reading
Section titled “Further reading”- Handbook: More on Functions: parameters, overloads, rest and
this. - Handbook: Everyday Types: function annotations.