Skip to content
dreamcode
dreamcode
Map
Inference
Lesson 2 of 26
+15 XP on finish
TS BASICSChapter 1 · TS Basics

Type Inference

You rarely need to annotate everything. TypeScript infers types from values: let stars = 100 is a number with no annotation at all, and a function's return type is inferred from what it returns. Once a variable's type is inferred it is fixed, so assigning text to stars later is an error. Annotate function parameters (they cannot be inferred) and places where you want to state your intent.

Worked example

How it reads

  • stars is inferred as number from its first value
  • double has no return annotation, but TypeScript knows it returns a number
  • Parameters like n still need an annotation
Common mistakes
  • let x; with no value and no annotation becomes any, and TypeScript stops checking it. Give it a type or a starting value.
Cloud tip: Let inference handle local variables, and annotate the edges: parameters and public function return types.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Write a function describe(name: string, moons: number), without a return annotation, that returns a sentence. Log describe("Mars", 2): Mars has 2 moons.

Press Run to check your work.