0
0
Typescriptprogramming~10 mins

Type annotation on variables in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Type annotation on variables
Declare variable
Add type annotation
Assign value matching type
Use variable safely
Compile-time check
Error if type mismatch
End
This flow shows how a variable is declared with a type, assigned a value, and checked by the compiler for type correctness.
Execution Sample
Typescript
let age: number;
age = 25;
console.log(age);
Declare a variable 'age' with type number, assign 25, then print it.
Execution Table
StepActionVariableType AnnotationValueCompiler CheckOutput
1Declare variableagenumberundefinedOK (no value yet)
2Assign value 25agenumber25OK (25 is number)
3Print valueagenumber25OK25
4Assign string 'hello'agenumbererrorError: Type 'string' is not assignable to type 'number'
💡 Execution stops at step 4 due to type mismatch error.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4
ageundefined2525error
Key Moments - 2 Insights
Why does assigning a string to 'age' cause an error?
Because 'age' is declared with type 'number', assigning a string violates the type annotation, as shown in execution_table step 4.
Can we declare a variable without assigning a value immediately?
Yes, as in step 1, 'age' is declared with type 'number' but has no value yet (undefined). The compiler allows this.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'age' after step 2?
A25
Bundefined
C'hello'
Derror
💡 Hint
Check the 'Value' column in execution_table row for step 2.
At which step does the compiler detect a type error?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the 'Compiler Check' column in execution_table for the error message.
If we remove the type annotation ': number' from 'age', what happens at step 4?
AError still occurs
BNo error, string assigned successfully
CVariable becomes readonly
DCompiler warns but allows assignment
💡 Hint
Without type annotation, TypeScript infers type or allows any type, so no error at step 4.
Concept Snapshot
Type annotation syntax: let variableName: type;
Assign values matching the type only.
Compiler checks types at compile time.
Errors occur if assigned value type mismatches.
Allows safer code by catching mistakes early.
Full Transcript
This example shows how to add a type annotation to a variable in TypeScript. We declare 'age' as a number, assign 25, and print it. The compiler checks that the assigned value matches the declared type. If we try to assign a string to 'age', the compiler gives an error and stops execution. This helps catch mistakes early and makes code safer.