Suggest an editImprove this articleRefine the answer for “Typing function parameters”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)Function parameters in TypeScript are typed directly in the declaration - `function functionName(param1: Type1, param2: Type2): ReturnType`, specifying the type of each parameter and, if needed, the return type. **Key point:** a parameter can be made optional (`age?: number`) or given a default value (`age: number = 18`) - in both cases its type is inferred with `undefined` or the default value taken into account.Shown above the full answer for quick recall.Answer (EN)Image## 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` -> the `name` parameter must be a string - `age: number` -> the `age` parameter 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 age ``` > The type of `age` here automatically becomes `number | 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 it ``` --- ## 5. 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); // 15 ``` --- ## 7. 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 = string ``` --- ## Summary | 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) ); ```For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.