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.
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.