Menu

Type Annotations and Type Inference

Lesson 1: Type Annotations and Type Inference

What is the difference?

Approach What it is Example
Type annotation You write the type explicitly let stock: number = 25;
Type inference TypeScript works out the type from the value let stock = 25; // number

TypeScript infers types from initial values, return statements, and the context a value is used in.

Example

let storeName = 'QuickCart';     // inferred: string
let deliveryFee = 40;            // inferred: number
let isOpen = true;               // inferred: boolean

storeName = 42;
// Error: Type 'number' is not assignable to type 'string'.

const prices = [64, 645, 60];    // inferred: number[]
const total = prices.reduce((a, b) => a + b, 0); // inferred: number

Where annotations are needed:

// Parameters are not inferred from calls
function addDeliveryFee(subtotal: number): number {
  return subtotal + 40;
}

// Variables declared before they get a value
let couponCode: string;
couponCode = 'FRESH10';

How it works

Situation Annotate? Why
Variable with an initial value Usually no Inference is accurate
Function parameters Yes TypeScript cannot guess what callers will pass
Function return types Optional; recommended for exported functions Documents intent and catches mistakes inside the function
Empty arrays or variables declared without a value Yes Otherwise the type is too wide or any
Callback parameters (.map(item => ...)) Usually no Inferred from context

Hover over any variable in your editor to see its inferred type.

Common mistakes

Mistake Effect Fix
const items = []; then pushing products Type is never[] or any[] const items: Product[] = [];
Annotating every variable Noisy, harder to read Let simple values be inferred
Missing parameter types Implicit any error under strict Annotate every parameter

Key takeaways

  • Let TypeScript infer variables; annotate parameters, empty collections, and exported return types.
  • Hover to see what TypeScript inferred.

Try it: Write five variables without annotations, hover over each to see the inferred type, then write a function with annotated parameters.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details