Array Literals Inferred as Mutable Arrays
You'll learn: Why TypeScript infers array literals with wider types than you might expect, and how this can cause problems when you need exact literal types.
The Broad Inference Problem
When you create an array literal in TypeScript, the type system makes a safe assumption: you'll probably want to modify it. So instead of inferring the exact literal values, TypeScript infers a mutable array of the general type.
const colors = ["red", "green", "blue"];
// Inferred as: string[]
// NOT: ["red", "green", "blue"]
This is type widening in action. TypeScript sees string literals but infers string[] because arrays are mutable—you can push, pop, and reassign elements. If it locked you into exact literals, normal array operations would break.
Why This Causes Issues
The problem appears when you need those specific literal types:
const colors = ["red", "green", "blue"];
function setColor(color: "red" | "green" | "blue") {
// ...
}
setColor(colors[0]); // Error! string is not assignable to "red" | "green" | "blue"
Even though colors[0] is clearly "red", TypeScript only knows it's some string because colors is string[].
The Analogy
Think of it like a box labeled "contains fruit" versus "contains exactly: 1 apple, 2 oranges." TypeScript chooses the general label by default because it assumes you'll be adding and removing fruit.
Key Takeaway: TypeScript infers array literals as mutable arrays of broader types (string[], number[]) rather than preserving exact literal types, which can cause type mismatches when specific literals are required.