0
0
Typescriptprogramming~20 mins

Why generics are needed in Typescript - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generics Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this TypeScript code using generics?

Look at this function that uses a generic type T. What will it print?

Typescript
function identity<T>(arg: T): T {
  return arg;
}

console.log(identity<string>("hello"));
ATypeError at runtime
Bnull
Cundefined
D"hello"
Attempts:
2 left
💡 Hint

Generics let the function keep the type of the input and output the same.

🧠 Conceptual
intermediate
1:30remaining
Why use generics instead of 'any' in TypeScript?

Choose the best reason why generics are better than using any type.

AGenerics make the code run faster at runtime.
BGenerics keep type information, so errors can be caught before running the code.
CGenerics allow using variables without declaring them.
DGenerics automatically convert types to strings.
Attempts:
2 left
💡 Hint

Think about how TypeScript helps catch mistakes before the program runs.

Predict Output
advanced
2:00remaining
What is the output of this generic function with arrays?

What will this code print?

Typescript
function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

console.log(firstElement([10, 20, 30]));
console.log(firstElement(['a', 'b', 'c']));
A
undefined
undefined
B
[10, 20, 30]
['a', 'b', 'c']
C
10
a
DTypeError at runtime
Attempts:
2 left
💡 Hint

The function returns the first item of the array.

🔧 Debug
advanced
2:00remaining
What error does this code produce and why?

Look at this code. What error will it cause?

Typescript
function wrapInArray<T>(value: T): T[] {
  return value;
}

const result = wrapInArray(5);
console.log(result);
AType 'number' is not assignable to type 'number[]'.
BNo error, prints [5].
CRuntime error: undefined is not iterable.
DSyntaxError: missing return statement.
Attempts:
2 left
💡 Hint

The function promises to return an array but returns a single value.

🧠 Conceptual
expert
2:30remaining
Why are generics important for reusable components in TypeScript?

Pick the best explanation for why generics help when building reusable components.

AGenerics allow components to work with many types while keeping type safety and avoiding code duplication.
BGenerics force all components to use the same type everywhere.
CGenerics automatically generate UI elements without coding.
DGenerics make components run faster by compiling to machine code.
Attempts:
2 left
💡 Hint

Think about how you can write one component that works with different data types safely.