Types and inference

Let TypeScript infer obvious types

Use inference for initialized local values and add annotations at boundaries where they make a contract clearer.

TypeScript reads initial values and infers types from them.

const course = 'TypeScript'
let status = 'draft'

Because course cannot be reassigned, TypeScript can keep the literal type 'TypeScript'. The mutable status variable widens to string because another string can replace it later.

Writing let status: string = 'draft' repeats what TypeScript already knows.

Inference also follows expressions:

const lessons = 42
const label = `${lessons} lessons`

Hover over the values. The editor should show a numeric type for lessons and a string type for label.

Annotations are useful where the intended contract is not obvious: function inputs, exported APIs, empty collections, and values whose allowed type is wider than the initializer.

My advice is to let local implementation details infer their types. Add annotations where they communicate a decision.

Exercise: change const course to let course and inspect how its inferred type changes.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →