Typing function parameters
1. General syntax
javascript
function functionName(param1: Type1, param2: Type2, ...): ReturnType {
// function body
}Example: simple parameter typing
javascript
function greet(name: string, age: number): void {
console.log(`Hello, ${name}! You are ${age} years old.`);
}name: string-> thenameparameter must be a stringage: number-> theageparameter must be a number: void-> the function returns nothing
2. Typing the return value
The type after ) specifies what the function returns:
javascript
function sum(a: number, b: number): number {
return a + b;
}- input: two numbers
- output: a number (
number)
If you do not specify the type, TypeScript infers it from the
return, but stating it explicitly makes the code clearer and safer.
3. Optional parameters (?)
If a parameter may be absent, add ?:
javascript
function greet(name: string, age?: number): void {
console.log(`Hello, ${name}${age ? ", you are " + age + " years old" : ""}.`);
}
greet("Tim"); // without age
greet("Alex", 25); // with ageThe type of
agehere automatically becomesnumber | undefined.
4. Parameters with a default value
If you set a default value, the parameter also becomes optional, and its type is inferred automatically:
javascript
function greet(name: string, age: number = 18): void {
console.log(`${name}, you are ${age} years old.`);
}
greet("Tim"); // uses 18
greet("Alex", 30); // overrides it5. Typing parameters of functions that accept arrays or objects
javascript
function printNames(names: string[]): void {
console.log(names.join(", "));
}
function showUser(user: { name: string; age: number }): void {
console.log(`${user.name}, ${user.age}`);
}
printNames(["Tim", "Alex"]);
showUser({ name: "Tim", age: 24 });6. Passing a function as a parameter
You can pass another function as a parameter, and give it a type (a signature):
javascript
function calculate(a: number, b: number, operation: (x: number, y: number) => number): number {
return operation(a, b);
}
const result = calculate(5, 3, (x, y) => x * y);
console.log(result); // 157. Using type for readability
javascript
type MathOp = (a: number, b: number) => number;
function applyOperation(a: number, b: number, op: MathOp): number {
return op(a, b);
}
applyOperation(4, 2, (x, y) => x / y);8. An example with generic parameters
If a function needs to work with different types, use <T>:
javascript
function identity<T>(value: T): T {
return value;
}
const num = identity(42); // T = number
const text = identity("hello"); // T = stringSummary
| Feature | Example | Description |
|---|---|---|
| A simple parameter | (name: string) | accepts a string |
| Multiple parameters | (a: number, b: number) | accepts 2 numbers |
| An optional parameter | (age?: number) | the parameter can be omitted |
| A parameter with a default value | (age: number = 18) | the value is substituted automatically |
| A function parameter | (cb: (x: number) => void) | accepts a function |
| A generic parameter | <T>(value: T) | accepts a value of any type |
An "all together" example:
javascript
function fetchData<T>(
url: string,
onSuccess: (data: T) => void,
onError?: (error: string) => void
): void {
try {
const mockData = JSON.parse('{"name":"Tim"}') as T;
onSuccess(mockData);
} catch {
onError?.("Parsing error");
}
}
fetchData<{ name: string }>(
"/api/user",
(data) => console.log(data.name),
(err) => console.error(err)
);Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.