MediumConcept

How does TypeScript type inference work?

Technology:
TypeScript
Experience:
Mid-level,
Senior

Quick answer

TypeScript fills in types you omit: literals get their literal or widened type, function return types are inferred from return statements, and generic arguments are inferred from the values you pass.

Detailed explanation

let count = 0 becomes number. const role = "admin" stays the literal "admin" because const cannot be reassigned. Contextual typing works the other way: a callback argument is inferred from the function you pass it to (arr.map(item => ...)).

Write types at module boundaries (function arguments, exported APIs, public class fields) and let inference handle locals. Over-annotating locals makes refactors noisy. When inference widens too far ([] is any[] without a hint), give the generic or a typed empty value ([] as User[] or User[] = []).

  • TypeScriptMedium

    What are generics in TypeScript?

    Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What are utility types in TypeScript like Partial, Pick and Omit?

    Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What is type narrowing in TypeScript?

    Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

    Mid-level 路 Senior 路 Types & Type System
  • TypeScriptMedium

    What is the difference between enum and union types in TypeScript?

    A string union such as "admin" | "user" exists only in the type system and erases to plain strings. A TypeScript enum compiles to a JavaScript object (unless it is a const enum), which is extra runtime code and a weaker default.

    Mid-level 路 Senior 路 Types & Type System