0
0
Typescriptprogramming~20 mins

Callback function types in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Callback Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a typed callback function
What is the output of this TypeScript code when the callback is called?
Typescript
function processNumber(num: number, callback: (n: number) => number): number {
  return callback(num * 2);
}

const result = processNumber(5, (x) => x + 3);
console.log(result);
A13
B16
C10
D8
Attempts:
2 left
💡 Hint
Remember the callback receives num * 2 and adds 3.
Predict Output
intermediate
2:00remaining
Return type of a callback with void
What will be logged when this TypeScript code runs?
Typescript
function executeCallback(cb: (msg: string) => void) {
  cb('Hello');
  return 'Done';
}

const output = executeCallback((text) => console.log(text.length));
console.log(output);
AHello\nDone
B5\nDone
Cundefined\nDone
D5\nundefined
Attempts:
2 left
💡 Hint
The callback logs the length of the string, then the function returns 'Done'.
🔧 Debug
advanced
2:00remaining
Identify the type error in callback usage
Which option shows the correct callback type to fix the TypeScript error in this code?
Typescript
function fetchData(callback: (data: string) => void) {
  callback('data loaded');
}

fetchData((info: number) => console.log(info));
A(info: string) => void
B() => void
C(info: any) => string
D(info: number) => void
Attempts:
2 left
💡 Hint
The callback expects a string parameter, not a number.
📝 Syntax
advanced
2:00remaining
Correct callback type syntax
Which option correctly types a callback that takes two numbers and returns a boolean?
A(a: number, b: number) => { return boolean; }
Bfunction(a: number, b: number): boolean
C(a: number, b: number): boolean => {}
D(a: number, b: number) => boolean
Attempts:
2 left
💡 Hint
Arrow function type syntax uses '=>' without function body.
🚀 Application
expert
3:00remaining
Using callback types with optional parameters
Given this function, which callback type allows the second parameter to be optional?
Typescript
function operate(x: number, y: number, cb: (a: number, b?: number) => number) {
  return cb(x, y);
}

const result = operate(4, 5, (m, n) => n ? m + n : m);
console.log(result);
A(a: number, b?: number | undefined) => void
B(a: number, b: number) => number
C(a: number, b?: number) => number
D(a: number) => number
Attempts:
2 left
💡 Hint
Optional parameters use '?' after the parameter name.