Skip to content
tsCheatSheet
GitHub

Functions

Return Type

//`: number` specifies this function returns a number
function getTime(): number {
	return new Date().getTime();
}

Return type void; doesn’t return any value

function printString(): void {
	console.log('Hello World!'); // prints "Hello World!"
	// but doens't return any value
}

Parameters

Function parameters can be typed, but they can also be inferred

function add(a: number, b: number) {
	// typed parameters
	return a + b;
}

Optional Parameters

// the `?` marks parameter `z` as optional
function multiply(x: number, y: number, z?: number) {
	return x + y + (z || 0);
}
console.log(add(3, 6)); // 9 since we didn't pass a `z`
console.log(add(3, 6, 9)); // 18 since we passed a `z`

Default Parameters

function pow(value: number, exponent: number = 4) {
	return value ** exponent;
}

The type can also be inferred from the default value

Named Parameters

Same as typing regualr parameters, but with an object

function divide({ dividend, divisor }: { dividend: number; divisor: number }) {
	return dividend / divisor;
}

Rest Parameters

Same as typing regular parameters, but with an array

function subtract(x: number, y: number, ...rest: number[]) {
	console.log(x - y - rest.reduce((a, b) => a - b, 0));
}

subtract(1, 2, 3, 4, 5);

Type Aliases

type Aliased = (value: number) => number;

// For this function, parameter `value` is automatically assigned
// type `number` from type `Aliased`
const aliasedFunction: Aliased = (value) => value \* -1;