Type inference is TypeScript figuring out types automatically from context, so you don't have to annotate everything. It infers from initial values, return statements, and usage.
ts
x = ;
s = ;
arr = [, ];
obj = { : , : };
Type inference is TypeScript figuring out types automatically from context, so you don't have to annotate everything. It infers from initial values, return statements, and usage.
x = ;
s = ;
arr = [, ];
obj = { : , : };
function double(n: number) { return n * 2; } // return inferred as number
[1, 2, 3].map(n => n * 2); // `n` inferred as number from the array — no annotation needed
This contextual typing is why callbacks rarely need parameter annotations — TypeScript knows map on a number[] passes a number.
let a = "hello"; // widened to string (let can be reassigned)
const b = "hello"; // narrowed to the literal type "hello"
const infers the literal type because it can never change; let widens to the general type. This matters for unions:
const dir = "up"; // type "up"
let dir2 = "up"; // type string
string not the literal).const xs = [] infers any[] — annotate as number[].Inference keeps TypeScript code nearly as concise as JavaScript while staying fully typed.
Understanding when it kicks in (and when it widens) lets you annotate only where it actually helps.
Knjižnica IT pitanja za razgovore za posao s detaljnim odgovorima — od Juniora do Seniora.
Doniraj