What is the output of this TypeScript code using a generic interface?
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);Think about the types of the content property in each box.
The numberBox.content is a number, so typeof returns "number". The stringBox.content is a string, so typeof returns "string". The console.log prints both separated by a space.
Why are generic interfaces important in TypeScript?
Think about how generics help avoid repeating similar interfaces for different types.
Generic interfaces let you write one interface that can handle many types, making your code more flexible and reusable.
What error will this TypeScript code produce?
interface Container<T> {
value: T;
}
const c: Container = { value: 42 };Check if the generic type parameter is provided when using the interface.
The interface Container requires a type argument like Container. Omitting it causes a TypeScript error.
Which option correctly defines a generic interface with two type parameters?
Remember how to separate multiple generic parameters in TypeScript.
Generic parameters must be separated by commas inside angle brackets. Option B is correct syntax.
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" });
Look at how the generic type T is inferred from the argument.
The generic type T is inferred as { id: number; name: string }. So result has data of that exact type.