0
0
Typescriptprogramming~20 mins

Why typed functions matter in Typescript - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Typed Functions 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 typed function?
Consider this TypeScript function with explicit types. What will be printed 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 the function return type and how the argument is used.
🧠 Conceptual
intermediate
1:00remaining
Why do typed functions help catch errors early?
Which of these best explains why typed functions are useful in TypeScript?
AThey help catch mistakes before running the code by checking types.
BThey automatically fix bugs in the code.
CThey allow the program to run faster at runtime.
DThey make the code shorter and harder to read.
Attempts:
2 left
💡 Hint
Think about when type errors are found.
🔧 Debug
advanced
1:30remaining
What error does this typed function cause?
Look at this TypeScript function. What error will the compiler show?
Typescript
function add(a: number, b: number): number {
  return a + b + '5';
}
ANo error, returns a string
BTypeError at runtime
CCompilation error: Type 'string' is not assignable to type 'number'
DCompilation error: Missing return statement
Attempts:
2 left
💡 Hint
Check the return type and what is being returned.
📝 Syntax
advanced
1:30remaining
Which typed function syntax is correct?
Which option shows a correct TypeScript function with typed parameters and return type?
Afunction multiply(a: number, b: number): string { return a * b; }
Bfunction multiply(a, b): number { return a * b; }
Cfunction multiply(a: number, b: number) { return a * b; }
Dfunction multiply(a: number, b: number): number { return a * b; }
Attempts:
2 left
💡 Hint
Check parameter and return type annotations.
🚀 Application
expert
2:00remaining
What is the output of this typed function using union types?
What will this TypeScript function print when called with 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
CTypeError at runtime
DCompilation error due to union type
Attempts:
2 left
💡 Hint
Look at how the function handles number and string types differently.