0
0
Typescriptprogramming~10 mins

Explicit type annotations in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Explicit type annotations
Declare variable
Add explicit type annotation
Assign value matching type
Use variable safely
Compile-time check for type errors
Run program if no errors
This flow shows how declaring a variable with an explicit type helps catch errors before running the program.
Execution Sample
Typescript
let age: number;
age = 25;
console.log(age);
Declare a variable with type number, assign a number, then print it.
Execution Table
StepActionVariableType AnnotationValueResult
1Declare variableagenumberundefinedVariable 'age' created with type number, no value yet
2Assign valueagenumber25Value 25 assigned to 'age', matches type number
3Print valueagenumber25Output: 25
4End---Program ends successfully
💡 No type errors, program runs and prints 25
Variable Tracker
VariableStartAfter Step 2Final
ageundefined2525
Key Moments - 2 Insights
Why do we write ': number' after 'age'?
The ': number' tells TypeScript that 'age' must always hold a number. This helps catch mistakes early, as shown in step 2 where the value assigned must match this type.
What happens if we assign a string to 'age'?
TypeScript will show an error before running the program because the assigned value does not match the declared type 'number'. This prevents bugs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'age' after step 1?
Anull
B25
Cundefined
Dnumber
💡 Hint
Check the 'Value' column in row for step 1 in the execution table.
At which step does 'age' get assigned the value 25?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Value' columns in the execution table.
If we change the type annotation to ': string' but assign 25, what happens?
AProgram runs and prints 25
BTypeScript shows a type error before running
CValue changes to '25' string automatically
DNo effect, code runs normally
💡 Hint
Refer to the key moment about assigning wrong types and the compile-time check step.
Concept Snapshot
Explicit type annotations in TypeScript:
- Syntax: let variableName: type;
- Forces variable to hold only that type
- Helps catch errors before running
- Example: let age: number;
- Assigning wrong type causes compile error
Full Transcript
This example shows how to declare a variable with an explicit type annotation in TypeScript. First, we declare 'age' with type 'number'. Then we assign the value 25 to it. The program prints 25. The explicit type helps TypeScript check that only numbers are assigned to 'age'. If we try to assign a different type, TypeScript will show an error before running the program. This prevents bugs and makes code safer.