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.

Function Expression: An anonymous function assigned to a variable, with types for parameters and return value.

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:

2. What are optional and default parameters in TypeScript functions?

Optional Parameters: Parameters that can be omitted, marked with ?. Must come after required parameters.

Default Parameters: Parameters with a default value, used if no value or undefined is passed.

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.

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.

Type Aliases: Named types created with the type keyword, often used for function signatures or complex types.

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:

  1. Create the project structure.
  2. Install dependencies: npm install.
  3. Compile: npm run build.
  4. Run: npm start.

Output:

[INFO] System started
[ERROR] Error occurred
Data: 1, 2, 3
Values: 4, 5, 6
20
15

Description:

6. What are common mistakes in TypeScript functions?

7. What are best practices for TypeScript functions?

  1. Declarations/Expressions:
    • Always specify parameter and return types for clarity and safety.
    • Use function expressions for typed variables or callbacks.
  2. Optional/Default Parameters:
    • Place optional parameters after required ones.
    • Use default parameters for common values; handle undefined for optional parameters.
  3. Rest Parameters:
    • Type rest parameters as type[] for clarity.
    • Validate or handle empty rest parameters.
  4. Function Types/Type Aliases:
    • Use type aliases for reusable function signatures.
    • Define function types for callbacks or higher-order functions.
  5. General:
    • Follow TypeScript naming conventions (e.g., camelCase for functions).
    • Use void for 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.json with strict settings (e.g., "strict": true) for robust type checking.