0
0
Typescriptprogramming~20 mins

Parameter type annotations in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Parameter Type Annotation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a function with parameter type annotations
What is the output of this TypeScript code when calling greet('Alice')?
Typescript
function greet(name: string): string {
  return `Hello, ${name}!`;
}

console.log(greet('Alice'));
AHello, undefined!
BHello, Alice!
CTypeError at runtime
DCompilation error due to missing return type
Attempts:
2 left
💡 Hint
Look at how the parameter name is typed and how the function returns a string.
Predict Output
intermediate
2:00remaining
Effect of wrong parameter type annotation
What happens when you call square('5') with this function?
Typescript
function square(num: number): number {
  return num * num;
}

console.log(square('5' as any));
A25
BTypeError at runtime
CCompilation error due to wrong argument type
DNaN
Attempts:
2 left
💡 Hint
The argument is forced to any type, so the function runs but with a string.
🔧 Debug
advanced
2:00remaining
Identify the error in parameter type annotation
What error does this TypeScript code produce?
Typescript
function add(a: number, b: string): number {
  return a + b;
}
ANo error, code runs fine
BTypeError: Cannot add number and string
CType 'string' is not assignable to type 'number' in return statement
DSyntaxError: Missing colon after parameter
Attempts:
2 left
💡 Hint
Check the return type and the expression inside the function.
📝 Syntax
advanced
2:00remaining
Correct parameter type annotation syntax
Which option shows the correct way to annotate a function parameter as an optional string in TypeScript?
Afunction greet(?name: string) {}
Bfunction greet(name: optional string) {}
Cfunction greet(name: string?) {}
Dfunction greet(name?: string) {}
Attempts:
2 left
💡 Hint
Optional parameters use a question mark after the parameter name.
🚀 Application
expert
3:00remaining
Determine the type of parameter in a complex function
Given this function, what is the type of the parameter callback?
Typescript
function processData(callback: (data: string, count: number) => boolean): void {
  const result = callback('test', 3);
  console.log(result);
}
AA function that takes a string and a number and returns a boolean
BA function that takes a boolean and returns a string and number
CA boolean value
DA string and number tuple
Attempts:
2 left
💡 Hint
Look at the arrow function type annotation inside the parameter.