This interface uses two generic types to hold two different values.
Typescript
interface Pair<T, U> {
first: T;
second: U;
}
Sample Program
This program shows how one generic interface Container<T> can be used for different types like number and string. It avoids writing separate interfaces for each type.
The interface Pair<T> requires a type argument when used, like Pair<number>.
Step 2: Identify the error in the code
The variable pair is declared as Pair without specifying <T>, causing a TypeScript error.
Final Answer:
Missing type argument when using Pair -> Option D
Quick Check:
Generic interfaces need type arguments [OK]
Hint: Always specify type argument when using generic interfaces [OK]
Common Mistakes:
Omitting the generic type argument
Trying to mix types without union
Assuming interface limits property count
5. Given this generic interface and usage, what is the best way to ensure the data property can hold either a string or an array of strings without losing type safety?
interface Response<T> {
data: T;
}
const response1: Response<string> = { data: 'hello' };
const response2: Response = { data: ['hello', 'world'] };
// How to declare a variable that can hold either response1 or response2?
hard
A. Use a union type: Response
B. Use any type: Response<any>
C. Create two separate interfaces for string and string[]
D. Use Response<object> to cover both
Solution
Step 1: Understand the need for flexible but safe typing
We want a variable that can hold either a string or an array of strings, keeping type safety.
Step 2: Use union types with generics
Declaring Response<string | string[]> allows data to be either type safely.
Final Answer:
Use a union type: Response<string | string[]> -> Option A
Quick Check:
Union types + generics = flexible and safe [OK]
Hint: Use union types inside generics for multiple allowed types [OK]
Common Mistakes:
Using any loses type safety
Creating duplicate interfaces wastes code
Using object is too broad and unsafe
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.