function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const x = first([1, "a"]);
string | number | undefinedThe 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.
Read more
- Generics (https://www.typescriptlang.org/docs/handbook/2/generics.html)typescriptlang.org