bhylu.com

Advertisements

TypeScript Type Inference

TypeScript can infer a type from an initializer and from how an expression is used. Inference keeps ordinary code readable while preserving checks at the places where values change.

How it works

A mutable count initialized with 6 is inferred as number, so it may later hold 7. A constant string can retain a more specific literal type because the binding cannot be reassigned. Object properties may still be mutable even when their binding uses const. When an inferred type is too broad for a contract, add a deliberate annotation or a const assertion rather than assuming const freezes every nested value.

Run the code

Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.

For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.

Example

lesson.ts

let packets = 6;
packets += 1;
const state = "ready";
const summary = { packets, state };
console.log(summary.packets, summary.state);

Expected result

7 ready

The checker follows numeric addition and the object shape without annotations on each line. Inference is still checking; it is not the same as any. Hover information in an editor can explain the inferred types. If a value unexpectedly widens to string instead of a specific state name, inspect the declaration where that widening happened.