CodePark/ questions / Generics
START PRACTICINGPRACTICE
Frontend question · TypeScript › Generics

What is the type of x?

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}
const x = first([1, "a"]);
string | number | undefined

The answer is string | number | undefined. TypeScript infers the array literal [1, "a"] as (string | number)[]. So T is string | number, and the return type adds undefined.

number | undefined is wrong because TypeScript does not pick only the first element's type. (string | number)[] is wrong because that is the type of the argument, not of the returned element.