Skip to content

Functions

TypeScript lets you annotate a function’s parameter types and return type, so the compiler can catch mismatched arguments or incorrect usage of the return value before the code ever runs. Function types can also be written standalone (e.g. as a type alias) to describe callback shapes.

function add(a: number, b: number): number {
return a + b;
}
add(2, 3); // 5
// add(2, "3"); // Error: argument of type 'string' not assignable to 'number'
// Arrow function with types
const multiply = (a: number, b: number): number => a * b;
// A standalone function type, useful for callbacks
type BinaryOp = (a: number, b: number) => number;
function calculate(a: number, b: number, op: BinaryOp): number {
return op(a, b);
}
calculate(4, 5, add); // 9
calculate(4, 5, multiply); // 20

Relying on TypeScript to infer a function’s return type and being surprised when a refactor silently changes it β€” without an explicit return type annotation, changing the body’s logic can change the inferred return type without any error, propagating the mismatch to every caller.

// No explicit return type -- TypeScript infers `number`
function getDiscount(price: number) {
return price * 0.1;
}
// Later, someone "improves" it...
function getDiscount(price: number) {
return `${price * 0.1}`; // oops, now returns a string -- no error here!
}
// Every caller expecting a number now silently gets a string, discovered only downstream
// Fix: annotate the return type explicitly, so this change WOULD error immediately
function getDiscount(price: number): number {
return `${price * 0.1}`; // Error: string not assignable to number
}
  1. What does adding : number after a function’s parameter list specify?

    AnswerThe function's return type β€” TypeScript checks that every return statement matches it.
  2. Why might you write an explicit return type even when TypeScript can infer it?

    AnswerIt acts as a safety net β€” if a future code change accidentally alters what the function returns, the explicit annotation causes an immediate compile error instead of silently propagating the wrong type to callers.
  3. How do you write a standalone type for a function that takes two numbers and returns a number?

    Answertype BinaryOp = (a: number, b: number) => number;