EasyType System📖 Theory Question

What is type inference in TypeScript and when does it kick in?

💡

Hint

TypeScript deduces types automatically from context — assignments, return values, default parameters

Full Answer

Type inference is TypeScript's ability to automatically determine a value's type without an explicit annotation.

Where inference applies:

  • Variable initializationconst x = 42 infers number
  • Function return type — inferred from the return expression
  • Default parametersfunction greet(name = 'World') infers name: string
  • Destructuring — inferred from the source type
  • Generic instantiation — argument types drive the type parameter
// Variable initialization
const count = 0;       // inferred: number
const name = 'Alice';  // inferred: string
const active = true;   // inferred: boolean

// Function return
function add(a: number, b: number) {
  return a + b; // return type inferred as number
}

// Contextual typing — callback param inferred from array type
const nums = [1, 2, 3];
nums.forEach(n => console.log(n.toFixed(2))); // n inferred as number

// Generic inference
function identity<T>(value: T): T { return value; }
const result = identity('hello'); // T inferred as string
💡 Prefer inference over redundant annotations. Write const x = 42 not const x: number = 42. Annotate function parameters and public API shapes where inference can't help consumers.

More Type System Questions

EasyWhat is the difference between any, unknown, and never in TypeScript?EasyWhat are type assertions and when should you use them?EasyWhat is structural typing (duck typing) in TypeScript?EasyWhat are union types and intersection types? When do you use each?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint