Type Inference in TypeScript
Most of the types in a TypeScript codebase are types nobody wrote. That is type inference: the compiler reads the value you assigned and works out the type on its own. Annotate everything by hand and you get a slower codebase to edit, more diffs on every refactor, and types that drift away from the values they describe.
The trouble is that inference has rules, and the rules are not always the ones you would guess.
This page covers the ones that actually bite: how let and const disagree, where contextual
typing comes from, how generics get filled in at the call site, and the handful of places where
the compiler quietly hands you any and stops helping.
What type inference actually does
When you declare a variable with a value and no annotation, TypeScript gives it a type based on that value.
let projectName = 'typescript-pro'
const projectVersion = 5.9projectName is string. projectVersion is 5.9 — the literal, not number. Hover either one
in your editor and the compiler will tell you what it decided. That hover is the single most
useful debugging tool you have for inference, and most people never use it deliberately.
The practical rule: let inference do the work for local variables and return values, and annotate at the boundaries you want to stay stable — function parameters, exported APIs, and anything describing data that arrives from outside your program.
let vs const: widening
This is the first thing that surprises people, and it explains about half the "why is this
string?" questions.
let themeMutable = 'dark' // string
const themeFixed = 'dark' // 'dark'A const can never be reassigned, so the compiler keeps the narrow literal type. A let can be
reassigned, so TypeScript widens 'dark' up to string — otherwise the next line of your code
would be an error waiting to happen.
Widening matters the moment you pass that variable somewhere typed:
type ThemeName = 'dark' | 'light'
function applyTheme(theme: ThemeName) {
return `theme-${theme}`
}
applyTheme(themeFixed) // ✅ 'dark' fits ThemeName
// applyTheme(themeMutable)
// ❌ Error: Argument of type 'string' is not assignable to parameter of type 'ThemeName'.The fix is to tell the compiler what the variable is for:
let themeAnnotated: ThemeName = 'dark'
applyTheme(themeAnnotated) // ✅Now the annotation is the type, and reassignment to 'light' is still allowed. Annotating a let
is not a failure of inference — it is you supplying information the value alone cannot carry.
Objects and arrays widen too
Object literals get the same treatment, one level down. Every property is inferred, and every property widens.
const requestConfig = {
url: '/api/users',
retries: 3,
}
// { url: string; retries: number }requestConfig is const, but requestConfig.url is still string, not '/api/users'. The
binding is constant; the properties are not, so they widen exactly like a let would.
Arrays infer the union of everything in them:
[object Object]That union is called the best common type: TypeScript looks at every element, finds the narrowest type that covers all of them, and uses it. If the elements have nothing in common, you get a union of their shapes rather than an error.
const mixedShapes = [
{ kind: 'circle', radius: 2 },
{ kind: 'square', side: 3 },
]Reach for a discriminated union when that is the shape you actually wanted, rather than hoping inference produces it for you.
One array case deserves a warning. An empty array literal gives the compiler nothing to read, so it tracks an "evolving" array type that fills in from whatever you push. That evolution only works inside a single scope — pass the array to another function first and you are stuck with whatever it had inferred at that moment. If the array starts empty and matters, annotate it:
const emptyQueue: string[] = []
emptyQueue.push('first-job')More on what the compiler reads out of array literals in TypeScript Array Types.
Contextual typing: inference flowing backwards
Everything so far reads a type out of a value. Contextual typing goes the other direction: the compiler infers a value's type from the position it appears in.
const scores = [90, 72, 58]
const passing = scores.filter((score) => score > 60)Nobody annotated score. TypeScript knows scores is number[], knows filter takes a callback
whose first parameter is the element type, and fills in number. The same thing happens whenever
you assign a function to an annotated target:
type ClickHandler = (eventName: string, atMs: number) => void
const logClick: ClickHandler = (eventName, atMs) => {
console.log(eventName.toUpperCase(), atMs.toFixed(0))
}Both parameters are typed, and neither has an annotation. This is why typing the variable rather
than the parameters is usually the better trade: one annotation on logClick does the work of
two, and it stays correct when ClickHandler changes.
Contextual typing is also the reason an inline callback is typed but the same function extracted
to a standalone const is not. The context disappeared when you moved it.
Return types: inferred by default, annotated on purpose
Function return types are inferred from the return statements.
function formatPrice(cents: number) {
return (cents / 100).toFixed(2)
}
// returns stringLeave these alone most of the time. Two cases are worth an explicit annotation.
The first is a recursive function, where the compiler cannot infer a return type it is still in the middle of computing:
type TreeNode = { value: number; children: TreeNode[] }
function sumTree(node: TreeNode): number {
return node.value + node.children.reduce((total, child) => total + sumTree(child), 0)
}The second is a public API boundary. An inferred return type means any change inside the function silently changes the type your callers see. Writing the return type turns that into a compile error in the one file that should own it.
Generic inference at the call site
The deepest form of inference is the one generics run on. You write a type parameter, and TypeScript fills it in from the arguments at every call.
function firstItem<ItemType>(items: ItemType[]): ItemType | undefined {
return items[0]
}
const firstTag = firstItem(['alpha', 'beta']) // string | undefined
const firstCount = firstItem([1, 2, 3]) // number | undefinedNo type arguments are written anywhere, and both calls are precisely typed. Constraints make it sharper, because one parameter can be inferred in terms of another:
function pickKey<ObjectType, KeyName extends keyof ObjectType>(source: ObjectType, key: KeyName) {
return source[key]
}
const serverPort = pickKey({ host: 'localhost', port: 8080 }, 'port') // numberObjectType comes from the first argument, KeyName from the second, and the return type falls
out of both. The keyof operator is doing the connecting work here.
When inference has nothing to go on — a type parameter that appears only in the return position,
say — TypeScript falls back to the constraint, or to unknown if there is no constraint. That is
usually the moment to pass the type argument explicitly rather than fight it.
Inference also runs inside the type system, with the infer keyword in conditional types. That
is a different mechanism with its own rules, and it has its own page:
the infer keyword.
Keeping literal types: as const and const type parameters
Widening is the right default and the wrong one roughly a third of the time. as const turns it
off for a single expression.
const httpMethods = ['GET', 'POST', 'PUT'] as const
type HttpMethod = (typeof httpMethods)[number] // 'GET' | 'POST' | 'PUT'That pattern — one array of values, one union derived from it with
typeof — keeps a list of constants and its type in sync forever.
as const also makes everything it touches deeply readonly, which is covered in
TypeScript readonly.
Since TypeScript 5.0, a type parameter can ask for the same thing on behalf of its callers:
function defineRoutes<const RouteList extends readonly string[]>(routes: RouteList) {
return routes
}
const appRoutes = defineRoutes(['/home', '/about']) // readonly ['/home', '/about']The const modifier on RouteList means callers get literal types without writing as const at
every call. For library authors this is the difference between a helper people enjoy and one they
have to remember a ritual for.
satisfies: check a value without flattening it
An annotation checks a value and then replaces its inferred type with the annotation. That is often a downgrade.
type ColorConfig = Record<string, [number, number, number]>
const palette = {
brand: [12, 90, 240],
muted: [120, 120, 120],
} satisfies ColorConfig
const brandRed = palette.brand[0] // numberWith satisfies, the compiler verifies palette against ColorConfig and then keeps the inferred
type: palette.brand still exists as a known key, and it is still a three-element tuple. Write
const palette: ColorConfig instead and you get the check but lose the key names — every lookup
becomes a generic index. The full comparison lives in
the satisfies operator.
Where type inference stops helping
Three places account for nearly every "why is this any?" bug.
Parsed JSON. JSON.parse returns any by design, and any spreads through everything it
touches.
[object Object]Inference cannot help here — there is no value at compile time to read. Annotate the result, or better, validate it at runtime and let the validator produce the type.
Caught errors. Under useUnknownInCatchVariables (on by default with strict), a catch
variable is unknown, not Error:
try {
JSON.parse('nope')
} catch (caughtError) {
if (caughtError instanceof Error) {
console.log(caughtError.message)
}
}Anything can be thrown in JavaScript, so unknown is the honest type. Narrow it before you use it.
Implicit any parameters. A function parameter with no annotation and no context has nothing
to infer from. noImplicitAny turns that into an error, which is why it should be on.
The pattern across all three: inference needs a value or a context to read. When there is neither, it does not guess — it gives up, and your job is to supply what it is missing.
The short version
TypeScript type inference is not a convenience feature bolted onto a type system. It is how the
type system is meant to be used. Annotate your boundaries, let the compiler fill in the middle,
and learn the three rules that cover most surprises: let widens and const does not, callbacks
get their types from the position they sit in, and as const plus satisfies are how you keep a
narrow type when the default would throw it away.
When something is typed more loosely than you expected, hover it. The compiler will tell you exactly what it inferred, and the gap between that and what you wanted is always the bug.
Become a TypeScript Pro
Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges