Typing Functions
Type a function fully: its parameters, its return value, plus optional and default arguments.
What you will learn
- Type parameters and the return value
- Use optional parameters with ?
- Give parameters default values
Parameters in, a value out
A fully typed function says what goes in (each parameter) and what comes out (the return type, written after the parentheses).
function greet(name: string): string {
return 'Hi, ' + name + '!';
}
console.log(greet('Asha'));Note: Output:
Hi, Asha!
name: string types the input; : string after the parentheses types the output. Returning a number here would be an error.
Functions that return nothing: void
If a function just does something and returns no value, its return type is void:
function logError(message: string): void {
console.log('ERROR: ' + message);
}
logError('Disk full');Note: Output:
ERROR: Disk full
void means "this returns nothing". It is the right type for functions that only have a side effect, like logging.
Optional parameters with ?
Add a ? after a parameter name to make it optional. Inside the function it might be missing, so TypeScript treats it as "the type, or undefined":
function greetUser(name: string, title?: string): string {
if (title) {
return 'Hello, ' + title + ' ' + name;
}
return 'Hello, ' + name;
}
console.log(greetUser('Asha'));
console.log(greetUser('Asha', 'Dr'));Note: Output:
Hello, Asha
Hello, Dr Asha
The first call skips title entirely — allowed because of the ?. The second supplies it.
Default values
Instead of optional, you can give a parameter a default value used when the caller leaves it out:
function multiply(a: number, b: number = 2): number {
return a * b;
}
console.log(multiply(5)); // b defaults to 2
console.log(multiply(5, 10)); // b is 10Note: Output:
10
50
In the first call b was missing, so it became 2 (giving 5 × 2). In the second, b was 10. TypeScript infers b is a number from the default.
Watch out: An optional parameter must come after all required ones. function f(a?: string, b: number) is an error — the optional one cannot sit before a required one.
Tip: Use a default value when there is a sensible fallback (like b = 2). Use ? when "missing" is genuinely meaningful and you handle it yourself.
Q. What does the ? in function f(x: number, y?: number) mean?
✍️ Practice
- Write a typed
area(width: number, height: number): numberand call it. - Add an optional
unit?: stringparameter to a function and handle the missing case.
🏠 Homework
- Write a
makeLabelfunction with one required and one default parameter, and show two calls with their outputs.