0
0
Typescriptprogramming~20 mins

Parameters type in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Parameters Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function with typed parameters
What is the output of this TypeScript code when calling greet('Alice', 3)?
Typescript
function greet(name: string, times: number): string {
  return `${name} `.repeat(times).trim();
}

console.log(greet('Alice', 3));
A"Alice Alice Alice"
B"Alice3"
C"Alice Alice"
D"3 Alice"
Attempts:
2 left
💡 Hint
Look at how the repeat method works on strings.
Predict Output
intermediate
2:00remaining
Type error with wrong parameter type
What error will TypeScript show for this code?
Typescript
function multiply(a: number, b: number): number {
  return a * b;
}

multiply(5, '2');
AType error: Argument of type 'string' is not assignable to parameter of type 'number'.
BRuntime error: Cannot multiply number and string.
CNo error, output is 10.
DSyntax error: Missing semicolon.
Attempts:
2 left
💡 Hint
Check the types of arguments passed to the function.
🔧 Debug
advanced
2:00remaining
Why does this function cause a type error?
Identify the cause of the type error in this code snippet.
Typescript
function formatDate(date: Date, format: string = 'YYYY-MM-DD'): string {
  return date.toLocaleDateString(format);
}

formatDate(new Date());
AThe <code>Date</code> type is not imported.
BThe function is missing a return type annotation.
CThe <code>toLocaleDateString</code> method does not accept a string format parameter.
DThe default parameter value is invalid syntax.
Attempts:
2 left
💡 Hint
Check the official signature of toLocaleDateString.
📝 Syntax
advanced
2:00remaining
Correct parameter type for callback function
Which option correctly types the parameter of this callback function?
Typescript
function processItems(items: string[], callback: (item: string) => void) {
  items.forEach(callback);
}

processItems(['a', 'b'], (item) => console.log(item));
A(item: number) => void
B(item: string) => void
C(item: any) => string
D(item) => number
Attempts:
2 left
💡 Hint
The array contains strings, so the callback parameter should match that type.
🚀 Application
expert
3:00remaining
Determine the type of parameters in a generic function
Given this generic function, what is the type of parameter value when calling identity(42)?
Typescript
function identity<T>(value: T): T {
  return value;
}

const result = identity(42);
Aunknown
Bstring
Cany
Dnumber
Attempts:
2 left
💡 Hint
TypeScript infers the type from the argument passed.