Type inference in TypeScript
Topic 3 of 37 · 9 minFree lessonIn the last topic you wrote types by hand. Most of the time you don't have to. When a variable gets a value straight away, TypeScript works out its type from that value. This is called type inference, and it's why most TypeScript code looks a lot like JavaScript.
Types from values
Here, no types are written at all. TypeScript still knows exactly what each variable holds.
let city = "Lisbon";// ^? let city: stringlet year = 2025;// ^? let year: numberlet sunny = true;// ^? let sunny: booleanThe checks are as strict as with an annotation. city is a string now, so it can't take a number later.
let city = "Lisbon";city = 42;Inference works on whole expressions
TypeScript doesn't only look at plain values. It works out the type of any expression: a sum, a joined string, a comparison or a method call.
const price = 4.5;const total = price * 3;// ^? const total: numberconst label = "Total: " + total;// ^? const label: stringconst isBig = total > 10;// ^? const isBig: booleanconsole.log(label, isBig);Each result has the type you'd expect. A comparison like total > 10 always gives a boolean.
const gives an exact type
With const, the value can never change. So TypeScript gives it the most exact type it can: the value itself. A type that's one exact value is called a literal type.
const planet = "Mars";// ^? const planet: "Mars"let destination = "Mars";// ^? let destination: stringplanet will always be "Mars", so its type is "Mars". destination is a let, so it could change to any other string later. You'll see how useful literal types are in a later topic.
When to write a type yourself
Inference needs a value to work from. So write a type when there isn't one yet, as in the last topic. Also write one when the value doesn't show what you mean.
let answer: string;const guesses: number[] = [];answer = "blue";guesses.push(3);console.log(answer, guesses);An empty array [] gives no clue what will go in it. number[] means "an array of numbers", and you'll meet array types properly soon. Function parameters are the other big case, which you'll see in the Functions section.
const firstName: string = "Ana";const lastName = "Silva";console.log(firstName, lastName);Both lines give a string. The second one is shorter and equally safe.
// ^? line under it. In a code editor, hold the mouse over the name.Try it yourself
Run the code in the editor and answer 8 practice questions on type inference. It's free, you only need an account.