TypeScript Functions - Questions & Answers
1. What are function declarations and expressions in TypeScript, and how are types used?
Function Declaration: A named function defined using the function keyword, with explicit parameter and return types.
- Syntax:
function functionName(param: type): returnType { // body }
Function Expression: An anonymous function assigned to a variable, with types for parameters and return value.
- Syntax:
const functionName: (param: type) => returnType = function(param) { // body };
Types in Functions: TypeScript enforces parameter and return types at compile time, catching type errors before runtime.
Use Case: Ensuring type safety for calculations, API calls, or data processing.
Can you give an example of function declarations and expressions with types?
// Function Declaration
function add(a: number, b: number): number {
return a + b;
}
// Function Expression
const multiply: (x: number, y: number) => number = function(x, y) {
return x * y;
};
// Usage
console.log(add(5, 3)); // Output: 8
console.log(multiply(4, 2)); // Output: 8
Note:
addis a declaration with typed parameters (number) and return type (number).multiplyis an expression with a function type annotation.- TypeScript ensures
a,b,x,yare numbers and the return value is a number.
2. What are optional and default parameters in TypeScript functions?
Optional Parameters: Parameters that can be omitted, marked with ?. Must come after required parameters.
- Syntax:
param?: type.
Default Parameters: Parameters with a default value, used if no value or undefined is passed.
- Syntax:
param: type = defaultValue.
Type Safety: TypeScript enforces types for optional/default parameters and checks for undefined in optional cases.
Use Case: Flexible function signatures for varying input scenarios.
Can you give an example of optional and default parameters?
// Optional and Default Parameters
function greet(name: string, greeting?: string, prefix: string = "Mr."): string {
const message = greeting || "Hello";
return `${message}, ${prefix} ${name}!`;
}
// Usage
console.log(greet("kristal")); // Output: Hello, Mr. kristal!
console.log(greet("Sashi", "Hi")); // Output: Hi, Mr. Sashi!
console.log(greet("hari", "Hey", "Dr.")); // Output: Hey, Dr. hari!
3. What are rest parameters in TypeScript?
Rest Parameters: Allow a function to accept a variable number of arguments as an array, using the ... syntax.
- Syntax:
...param: type[].
Type Safety: TypeScript enforces that rest parameters are an array of a specific type.
Use Case: Handling dynamic numbers of inputs (e.g., summing numbers, logging messages).
Can you give an example of rest parameters?
// Rest Parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
// Usage
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(10)); // Output: 10
console.log(sum()); // Output: 0
4. What are function types and type aliases in TypeScript?
Function Types: Define the signature of a function, specifying parameter types and return type.
- Syntax:
(param: type) => returnType.
Type Aliases: Named types created with the type keyword, often used for function signatures or complex types.
- Syntax:
type AliasName = (param: type) => returnType.
Use Case: Reusing function signatures, ensuring consistent function types across variables or parameters.
Can you give an example of function types and type aliases?
// Function Types and Type Aliases
type MathOperation = (x: number, y: number) => number;
// Function using type alias
const add: MathOperation = (x, y) => x + y;
const subtract: MathOperation = (x, y) => x - y;
// Function accepting a function type
function applyOperation(x: number, y: number, operation: MathOperation): number {
return operation(x, y);
}
// Usage
console.log(applyOperation(5, 3, add)); // Output: 8
console.log(applyOperation(5, 3, subtract)); // Output: 2
5. Can you provide a comprehensive example of TypeScript functions?
Project Structure:
ts-functions/
├── src/
│ └── main.ts
├── tsconfig.json
└── package.json
main.ts:
// Comprehensive TypeScript Functions Example
type Logger = (message: string, level?: string) => string;
// Function Declaration with Optional Parameter
function logMessage(message: string, level?: string): string {
return `[${level || "INFO"}] ${message}`;
}
// Function Expression with Default Parameter
const processData: (data: number[], prefix: string) => string = function(
data,
prefix = "Data:"
) {
return `${prefix} ${data.join(", ")}`;
};
// Rest Parameters
function average(...numbers: number[]): number {
if (numbers.length === 0) return 0;
return numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
}
// Type Alias for Operation
type Operation = (a: number, b: number) => number;
// Function using Type Alias
function executeOperation(a: number, b: number, op: Operation): number {
return op(a, b);
}
// Example Usage
const multiply: Operation = (a, b) => a * b;
console.log(logMessage("System started")); // Output: [INFO] System started
console.log(logMessage("Error occurred", "ERROR")); // Output: [ERROR] Error occurred
console.log(processData([1, 2, 3])); // Output: Data: 1, 2, 3
console.log(processData([4, 5, 6], "Values:")); // Output: Values: 4, 5, 6
console.log(average(10, 20, 30)); // Output: 20
console.log(executeOperation(5, 3, multiply)); // Output: 15
package.json:
{
"name": "ts-functions",
"version": "1.0.0",
"scripts": {
"start": "tsc && node dist/main.js",
"build": "tsc",
"watch": "tsc --watch"
},
"devDependencies": {
"typescript": "^5.6.2"
}
}
tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Steps to Run:
- Create the project structure.
- Install dependencies:
npm install. - Compile:
npm run build. - Run:
npm start.
Output:
[INFO] System started
[ERROR] Error occurred
Data: 1, 2, 3
Values: 4, 5, 6
20
15
Description:
- Function Declaration:
logMessageuses optional parameterlevel. - Function Expression:
processDatauses a default parameterprefix. - Rest Parameters:
averagehandles variable numbers of inputs. - Type Alias:
Operationensures consistent function signatures forexecuteOperation.
6. What are common mistakes in TypeScript functions?
- Declarations/Expressions:
- Omitting type annotations, reducing type safety.
- Incorrect return type annotations, causing compile-time errors.
- Optional/Default Parameters:
- Placing optional parameters before required ones, causing syntax errors.
- Not handling
undefinedfor optional parameters.
- Rest Parameters:
- Not typing rest parameters as arrays, causing type mismatches.
- Passing incorrect types to rest parameters.
- Function Types/Type Aliases:
- Defining overly specific or generic function types, leading to inflexibility or errors.
- Not reusing type aliases for consistent function signatures.
- General:
- Ignoring TypeScript errors, leading to runtime issues.
- Overcomplicating function signatures with excessive parameters.
7. What are best practices for TypeScript functions?
- Declarations/Expressions:
- Always specify parameter and return types for clarity and safety.
- Use function expressions for typed variables or callbacks.
- Optional/Default Parameters:
- Place optional parameters after required ones.
- Use default parameters for common values; handle
undefinedfor optional parameters.
- Rest Parameters:
- Type rest parameters as
type[]for clarity. - Validate or handle empty rest parameters.
- Type rest parameters as
- Function Types/Type Aliases:
- Use type aliases for reusable function signatures.
- Define function types for callbacks or higher-order functions.
- General:
- Follow TypeScript naming conventions (e.g., camelCase for functions).
- Use
voidfor functions with no return value. - Leverage TypeScript's type inference where explicit types are redundant.
- Test with edge cases (e.g.,
undefined, invalid types). - Use
tsconfig.jsonwithstrictsettings (e.g.,"strict": true) for robust type checking.
Frequently asked questions
What are function declarations and expressions in TypeScript, and how are types used?
Function declarations use the function keyword with typed parameters and return type. Function expressions assign an anonymous function to a variable with a function type signature. Types ensure parameter and return value safety.
What are optional and default parameters in TypeScript functions?
Optional parameters (param?: type) can be omitted. Default parameters (param: type = value) use a default if undefined is passed. Optionals must come after required parameters.
What are rest parameters in TypeScript?
Rest parameters (...param: type[]) allow a function to accept any number of arguments as a typed array, ideal for variable-argument functions.
What are function types and type aliases in TypeScript?
Function types define signatures like (param: type) => returnType. Type aliases (type Name = ...) create reusable named function signatures for consistency.
Can you provide a comprehensive example of TypeScript functions?
Yes – full project demonstrating declarations, expressions, optional/default parameters, rest parameters, and type aliases in a practical setup.
What are common mistakes in TypeScript functions?
Omitting types, wrong parameter order for optionals, not typing rest as array, inconsistent function signatures, ignoring TypeScript errors.
What are best practices for TypeScript functions?
Always annotate types, use defaults wisely, type rest as arrays, reuse type aliases, enable strict mode, test edge cases.