Skip to content
tezvyn:
Menu

Refactor a function using generics to accept any array type

Source: typescriptlang.orgEasyHow cards are made

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's really being asked

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.

The full answer

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.

The mistakes people make

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.

What usually comes next

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.

A 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.

Interview question

Which TypeScript signature correctly refactors firstElement to preserve the array's element type while returning a single element?

  • a.function firstElement(arr: any[]): any
  • b.function firstElement<T>(arr: T[]): T[]
  • c.function firstElement<T>(arr: T[]): TCorrect
  • d.function firstElement(arr: unknown[]): unknown
Why?

Using T[] as the return type is a tempting mistake because it keeps the array wrapper instead of extracting the element, while any and unknown erase the specific type information entirely.

Just read this? Test yourself on what you have been reading.

Read the original → typescriptlang.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on typescript — each one lists the topics its interview covers.

See open roles