How @ts-check Uses Type Inference
What you'll learn: How TypeScript's compiler analyzes your plain JavaScript code to infer types automatically when you add // @ts-check.
The Magic Behind @ts-check
When you add // @ts-check to the top of a JavaScript file, TypeScript doesn't just sit there waiting for you to annotate everything. It actively infers types by watching how you use your code—like a detective piecing together clues from your variable assignments, function returns, and usage patterns.
How Type Inference Works
TypeScript looks at three main sources to figure out what types your code is working with:
Variable assignments: If you write let count = 0, TypeScript infers count is a number. If you later try count = "five", @ts-check will flag it because the inferred type doesn't match.
Return values: When a function returns return x + y where both are numbers, TypeScript infers the function returns a number—even without @returns documentation.
Usage patterns: If you call name.toUpperCase(), TypeScript infers name must be a string (because only strings have that method). If you pass it to a function that uppercases strings, that function's parameter is inferred as expecting a string.
Why This Matters
This inference means you get type safety without writing JSDoc comments everywhere. TypeScript reads your existing JavaScript and builds a mental model of your types. You only need explicit annotations when the inference is ambiguous or when you want to be more specific than TypeScript can guess.
The inference works with your JSDoc comments too—wherever you've defined types with @type or @typedef, those feed into the inference system for even smarter checking.
Key Takeaway: TypeScript's type inference under @ts-check analyzes your code's behavior to automatically determine types, giving you safety checks without requiring extensive manual annotations.