0
0
Typescriptprogramming~20 mins

Type annotation on function parameters in Typescript - Practice Problems & Coding Challenges

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

console.log(greet('Alice'));
AError: Missing return type
B"Hello, Alice!"
CHello, Alice!
Dundefined
Attempts:
2 left
💡 Hint
Look at how the function returns a string and how console.log prints it.
Predict Output
intermediate
1:30remaining
What error does this code produce?
What error will this TypeScript code cause when compiled?
Typescript
function multiply(x: number, y: number): number {
  return x * y;
}

multiply('2', 3);
ATypeError at runtime
BNo error, returns 6
CSyntaxError
DTypeScript compile error: Argument of type 'string' is not assignable to parameter of type 'number'
Attempts:
2 left
💡 Hint
Check the types of arguments passed to the function.
🔧 Debug
advanced
2:00remaining
Why does this function cause a compile error?
This function is intended to add two numbers. Why does TypeScript report an error?
Typescript
function add(a, b: number): number {
  return a + b;
}
AParameter 'b' should be optional
BParameter 'a' has no type annotation, causing an implicit any error
CReturn type is missing
DFunction body is missing a return statement
Attempts:
2 left
💡 Hint
Check the types of all parameters.
Predict Output
advanced
1:30remaining
What is the output of this function with default parameter and type annotation?
What will this code print?
Typescript
function welcome(name: string = 'Guest'): string {
  return `Welcome, ${name}!`;
}

console.log(welcome());
AWelcome, Guest!
BWelcome, undefined!
CError: Missing argument
DWelcome, !
Attempts:
2 left
💡 Hint
Look at the default value for the parameter.
Predict Output
expert
2:30remaining
What is the output of this function using union types in parameters?
What will this code print when calling formatId(123) and formatId('abc')?
Typescript
function formatId(id: number | string): string {
  if (typeof id === 'number') {
    return `ID-${id.toFixed(0)}`;
  } else {
    return `ID-${id.toUpperCase()}`;
  }
}

console.log(formatId(123));
console.log(formatId('abc'));
A
ID-123
ID-ABC
B
ID-123.0
ID-abc
C
ID-123
ID-abc
DError: toFixed not available on number
Attempts:
2 left
💡 Hint
Check how the function handles number and string types differently.