Refactor a function using generics to accept any array type
It tests generic type parameters for preserving element types through a function boundary. Answer: declare T, accept T[], return T, and let the compiler infer the element type from the call site.
WHAT THIS TESTS: This question checks whether you understand generic type parameters as a mechanism for preserving type information across function boundaries. The interviewer wants to see if you can replace a concrete type with a type variable so that the relationship between the input array and the returned element is maintained by the compiler.
A GOOD ANSWER COVERS: A strong answer walks through four steps in order. First, introduce a type parameter T on the function. Second, change the parameter type from number[] to T[] or ReadonlyArray<T> if immutability matters. Third, set the return type to T instead of number. Fourth, explicitly mention that TypeScript will infer T from the argument at the call site, so passing an array of strings returns a string, passing an array of objects returns that object type, and no information is lost to any or unknown.
COMMON WRONG ANSWERS: The biggest red flag is changing the parameter to any[] and the return type to any, which defeats the purpose of TypeScript. Another mistake is typing the parameter as unknown[] and then forcing the caller to cast the result, which pushes type safety work onto consumers. Some candidates write multiple function overloads for string[], number[], and so on, which is unmaintainable and misses custom types entirely. A subtler error is returning T[] instead of T, which fails to match the requirement of returning the first element.
LIKELY FOLLOW-UPS: The interviewer may ask how you would handle an empty array, which opens a discussion of returning T or undefined and whether to use a generic with a constraint or a default. They might also ask about readonly arrays, tuple types, or how generics interact with inference in more complex signatures such as mapping functions. Another angle is asking why any[] is insufficient when the array contains mixed types, which leads to a conversation about union types and generic constraints.
ONE CONCRETE EXAMPLE: Imagine a function named firstElement. Before refactoring, it is declared as function firstElement(arr: number[]): number. After refactoring, it becomes function firstElement<T>(arr: T[]): T. When you call firstElement([1, 2, 3]), TypeScript infers T as number and the return type is number. When you call firstElement([{ id: 1 }, { id: 2 }]), T is inferred as { id: number }, so the return type is { id: number } without any manual annotation at the call site.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.