You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
Functions are the building blocks of any TypeScript application. TypeScript adds powerful type annotations to function parameters, return values, and overloads, making your code more predictable and self-documenting. This lesson covers every aspect of typing functions in TypeScript.
Always annotate function parameters. Return types can often be inferred, but adding them explicitly improves readability:
function add(a: number, b: number): number {
return a + b;
}
const multiply = (x: number, y: number): number => x * y;
If you omit the return type, TypeScript infers it from the return statements. However, explicit return types catch mistakes early — for example, accidentally returning undefined from a function that should always return a value.
Use ? to mark a parameter as optional. Optional parameters must come after required ones:
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}`;
}
return `Hello, ${name}`;
}
greet('Alice'); // 'Hello, Alice'
greet('Alice', 'Dr'); // 'Hello, Dr Alice'
Inside the function body, an optional parameter has a union type of its declared type and undefined.
Default parameter values provide a fallback when no argument is supplied:
function createUser(name: string, role: string = 'viewer'): { name: string; role: string } {
return { name, role };
}
createUser('Alice'); // { name: 'Alice', role: 'viewer' }
createUser('Bob', 'admin'); // { name: 'Bob', role: 'admin' }
When a default value is provided, TypeScript infers the parameter type from the default, so you do not need an explicit annotation (though you may still add one for clarity).
Rest parameters collect a variable number of arguments into an array:
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
sum(10, 20); // 30
Rest parameters must be the last parameter in the function signature.
You can type a variable as a function using arrow syntax:
type MathOperation = (a: number, b: number) => number;
const divide: MathOperation = (a, b) => a / b;
// As an interface:
interface StringTransformer {
(input: string): string;
}
const toUpper: StringTransformer = (input) => input.toUpperCase();
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.