🏷️ TypeScript - Functions
Functions
Updated at 2024-08-02 04:57
- Parameter refers to a function's declaration of what it expects.
- Argument refers to a value provided to a parameter in a function call.
Functions have a type like everything else.
type StringToNumber = (input: string) => number;
let stringToNumber: StringToNumber;
Functions can have variadic parameters.
function singAllTheSongs(singer: string, ...songs: string[]) {
for (const song of songs) {
console.log(`${song}, by ${singer}`);
}
}
Functions whose return type is void may not return a value.
Functions whose return type is never are never-returning. Never-returning functions are those that always throw an error or run an infinite loop.
function fail(message: string): never {
throw new Error(`Invariant failure: ${message}.`);
}
Overload signatures allows declaring different versions of a function. Overloads are used as the last resort for complex functions. It's generally better to keep your functions simple to avoid overloading.
// the last definition is the implementation
function createDate(timestamp: number): Date;
function createDate(month: number, day: number, year: number): Date;
function createDate(monthOrTimestamp: number, day?: number, year?: number) {
return day === undefined || year === undefined
? new Date(monthOrTimestamp)
: new Date(year, monthOrTimestamp, day);
}
You can use call signatures to type functions that also have properties.
interface FunctionWithCount {
(): void;
count: number;
}
let hasCallCount: FunctionWithCount;
// ok
function keepsTrackOfCalls() {
keepsTrackOfCalls.count += 1;
}
keepsTrackOfCalls.count = 0;
hasCallCount = keepsTrackOfCalls;
// error
function doesNotHaveCount() {
console.log("No idea!");
}
hasCallCount = doesNotHaveCount;
Sources
- Learning TypeScript by Josh Goldberg