Menu
Coddy logo textTech

Explicit Type Annotations

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 11 of 73.

Understanding when to use explicit annotations versus relying on inference is crucial for writing effective TypeScript code.

The most common scenario requiring explicit type annotations is when you declare a variable without immediately assigning it a value:

let score: number;  // Must specify type explicitly
score = 85;         // Assign value later

Without the explicit : number annotation, TypeScript would infer the type as any, losing all type safety benefits. By explicitly declaring the type, you ensure that only numeric values can be assigned to this variable later.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Declare a variable named totalScore with the explicit type number without assigning it an initial value.

On the next line, assign the value 95 to the totalScore variable.

Then declare another variable named playerName with the explicit type string without assigning it an initial value.

On the next line, assign the value "Alex" to the playerName variable.

Finally, print both variables to the console on separate lines, first totalScore then playerName.

Cheat sheet

When declaring variables without immediately assigning values, explicit type annotations are required to maintain type safety:

let score: number;  // Must specify type explicitly
score = 85;         // Assign value later

Without explicit annotation, TypeScript infers the type as any, losing type safety benefits.

Try it yourself

// TODO: Write your code here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript