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.
Try a preset
Inferred 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.