Skip to main content

Typing Functions

Unlike variables, TypeScript will not infer the types of function parameters automatically. They secretly default to any, which violates strict coding protocols.

You must explicitly define the type of data your parameters expect.

Parameter and Return Types

To structure a function logically, annotate the parameters within the parentheses, and annotate the Return Type directly after the closing parenthesis.

// (param: type): returnType
function multiply(x: number, y: number): number {
return x * y;
}

// Arrow function syntax
const divide = (x: number, y: number): number => {
return x / y;
};

If your function runs processes but DOES NOT inherently return anything at the very end, we type the return as void.

function logApplicationStart(): void {
console.log("App has booted up!");
}

Optional and Default Parameters

1. Optional Parameters

By default, TypeScript throws an error if you pass too few or too many arguments to a function. If an argument isn't strictly required, use the ? symbol right before the colon.

function greet(firstName: string, lastName?: string): string {
if (lastName) {
return `Hello ${firstName} ${lastName}`;
}
return `Hello ${firstName}`;
}

greet("Midhun"); // Valid
greet("Midhun", "Balan"); // Valid

2. Default Parameters

You can provide an absolute default value inline natively. Note that TypeScript is smart enough to infer the default parameters data type, so you don't even need the :!

// 'tax' is inferred strictly as a number because we defaulted it to 0.15
function calculateTotal(price: number, tax = 0.15): number {
return price + (price * tax);
}

calculateTotal(100); // Uses 0.15
calculateTotal(100, 0.20); // Overrides the default