0
0
Typescriptprogramming~20 mins

Why generic interfaces matter in Typescript - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Interface Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of generic interface usage

What is the output of this TypeScript code using a generic interface?

Typescript
interface Box<T> {
  content: T;
}

const numberBox: Box<number> = { content: 123 };
const stringBox: Box<string> = { content: "hello" };

console.log(typeof numberBox.content, typeof stringBox.content);
A"number string"
B"number number"
C"object object"
D"string number"
Attempts:
2 left
💡 Hint

Think about the types of the content property in each box.

🧠 Conceptual
intermediate
1:30remaining
Why use generic interfaces?

Why are generic interfaces important in TypeScript?

AThey allow defining reusable interfaces that work with any data type, improving code flexibility.
BThey enforce using only one specific data type in all interface instances.
CThey automatically convert all data types to strings inside the interface.
DThey prevent interfaces from being extended or reused.
Attempts:
2 left
💡 Hint

Think about how generics help avoid repeating similar interfaces for different types.

🔧 Debug
advanced
2:00remaining
Identify the error in generic interface usage

What error will this TypeScript code produce?

Typescript
interface Container<T> {
  value: T;
}

const c: Container = { value: 42 };
ANo error, code runs fine.
BError: Property 'value' is missing in type '{}'.
CError: Type 'number' is not assignable to type 'string'.
DError: Generic type 'Container<T>' requires 1 type argument(s).
Attempts:
2 left
💡 Hint

Check if the generic type parameter is provided when using the interface.

📝 Syntax
advanced
1:30remaining
Correct syntax for generic interface with multiple types

Which option correctly defines a generic interface with two type parameters?

Ainterface Pair<T U> { first: T; second: U; }
Binterface Pair<T, U> { first: T; second: U; }
Cinterface Pair<T; U> { first: T; second: U; }
Dinterface Pair<T> U { first: T; second: U; }
Attempts:
2 left
💡 Hint

Remember how to separate multiple generic parameters in TypeScript.

🚀 Application
expert
2:30remaining
Using generic interfaces to enforce type safety

Given this generic interface, what is the type of result after this code runs?

interface Response {
  data: T;
  error?: string;
}

function fetchData(input: T): Response {
  return { data: input };
}

const result = fetchData({ id: 1, name: "Alice" });
A{ data: object; error?: string | undefined }
B{ data: any; error?: string | undefined }
C{ data: { id: number; name: string }; error?: string | undefined }
D{ data: string; error?: string | undefined }
Attempts:
2 left
💡 Hint

Look at how the generic type T is inferred from the argument.