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 laterWithout 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyDeclare 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 laterWithout explicit annotation, TypeScript infers the type as any, losing type safety benefits.
Try it yourself
// TODO: Write your code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples