Back to questionsWhich types does TypeScript infer for
JuniorTheoryCommon
Which types does TypeScript infer for a and b?
function last<T>(xs: T[]): T {
return xs[xs.length - 1];
}
const a = last([1, 2, 3]);
const b = last(["x", "y"]);
console.log(a, b);number and string
- Expecting
Tfixed by the first call: inference starts over at each call, solast(["x", "y"])readsstringfrom its own argument. - Expecting
any, as in a function without a type parameter: TypeScript infersTfrom the argument, soais anumber.
- What type does
last([1, "a"])give, and why? - What does tsc report for
last<number>(["x"])?