TypeScript Type Inference Playground
Paste a TypeScript snippet and see how the TypeScript compiler would infer the type of every variable. This rule-based engine mirrors the real inference rules: literal widening, let versus const, unions from repeated assignments, array element unions, ternary branches, typeof narrowing and function return types.
| Variable | Declared | Inferred type | Notes |
|---|
How it works
- Literal widening:
let s = "hi"widens tostring, whileconst s = "hi"keeps the literal type"hi". - Unions: every assignment to the same variable adds to its type, so
let x = 1; x = "a"becomesstring | number. - Arrays: element types are merged into a union, for example
(string | number | boolean)[]. - Ternary:
cond ? 1 : "x"infersstring | numberfrom the two branches. - Narrowing: a
typeof x === "string"guard narrowsxtostringinside the block. - Functions: return statements are scanned and their expression types are merged into an inferred return type.
This is a simplified rule engine for learning purposes. The real TypeScript compiler also considers control flow, generics, context and declaration merging.
Frequently Asked Questions (FAQ)
What does the TypeScript Type Inference Playground show?
You paste a TypeScript snippet and the tool shows the inferred type of every variable in a table with columns for variable name, declaration kind, inferred type and explanatory notes.
Which TypeScript inference rules does it demonstrate?
The page covers literal widening, let versus const behavior, unions from repeated assignments, merged array element types, ternary branches, typeof narrowing and function return types.
What are the preset buttons for?
Six preset buttons fill the editor with ready examples: String widening, Const literal, Union assignment, Mixed array, Ternary and Typeof narrowing, so you can see each rule in action instantly.
Is this the real TypeScript compiler?
No, the page states it is a simplified rule engine for learning purposes. The real TypeScript compiler also considers control flow, generics, context and declaration merging.