Look at this function that uses a generic type T. What will it print?
function identity<T>(arg: T): T { return arg; } console.log(identity<string>("hello"));
Generics let the function keep the type of the input and output the same.
The function identity returns exactly what it receives. Using <string> tells TypeScript the input is a string, so it returns "hello".
Choose the best reason why generics are better than using any type.
Think about how TypeScript helps catch mistakes before the program runs.
Using any disables type checking, but generics keep the type info so TypeScript can warn about mistakes early.
What will this code print?
function firstElement<T>(arr: T[]): T | undefined { return arr[0]; } console.log(firstElement([10, 20, 30])); console.log(firstElement(['a', 'b', 'c']));
The function returns the first item of the array.
The function firstElement returns the first element of the array passed in. For numbers, it returns 10; for strings, it returns 'a'.
Look at this code. What error will it cause?
function wrapInArray<T>(value: T): T[] { return value; } const result = wrapInArray(5); console.log(result);
The function promises to return an array but returns a single value.
The function signature says it returns an array of T, but it returns value directly, which is just T. TypeScript reports a type mismatch.
Pick the best explanation for why generics help when building reusable components.
Think about how you can write one component that works with different data types safely.
Generics let you write flexible components that accept different types without losing the benefits of type checking, so you don't have to write the same code many times.