🌐 TypeScript – Variables
A variable is a named space in memory that stores values. It acts as a container for values in a program. In TypeScript, variables must follow JavaScript’s naming rules:
📜 Rules for Variable Naming:
- Variable names can contain alphabets and numeric digits.
- They cannot contain spaces and special characters (except for
_or$). - A variable name cannot begin with a digit.
- A variable must be declared before use.
🖋 Variable Declaration in TypeScript
To declare a variable in TypeScript, the type of the variable is specified after the variable name, using a colon :. Just like in JavaScript, we use the var keyword.
Here are the four ways to declare variables:
- Declare type and value in one statement:
var name: string = "Karim"; - Declare type but no value (value defaults to
undefined):var name: string; - Declare value but no type (TypeScript infers the type from the value):
var name = "Karim"; // type inferred as string - Declare neither value nor type (type is
any, initialized toundefined):var name; // type inferred as any
📝 Example: Variables in TypeScript
var name: string = "John";
var score1: number = 50;
var score2: number = 42.50;
var sum = score1 + score2;
console.log("name: " + name);
console.log("first score: " + score1);
console.log("second score: " + score2);
console.log("sum of the scores: " + sum);
Generated JavaScript code:
var name = "John";
var score1 = 50;
var score2 = 42.50;
var sum = score1 + score2;
console.log("name" + name);
console.log("first score: " + score1);
console.log("second score: " + score2);
console.log("sum of the scores: " + sum);
Output:
name: John
first score: 50
second score: 42.50
sum of the scores: 92.50
Strong Typing in TypeScript ensures that types on either side of the assignment operator = match. If you try assigning a value of a different type, TypeScript will throw an error:
var num: number = "hello"; // Compilation error
🧳 Type Assertion in TypeScript
Type Assertion allows you to change a variable from one type to another. This is useful when you know the type of a value better than TypeScript does.
Syntax:
Place the target type between < > symbols and place it in front of the variable or expression.
var str = '1';
var str2: number = <number> <any> str; // str is now treated as type number
console.log(str2);
Generated JavaScript:
var str = '1';
var str2 = str; // str is now treated as a number
console.log(str2);
Output:
1
Note: Type Assertion does not perform any type checking at runtime. It’s a compile-time feature to help TypeScript understand your code better.
🔍 Inferred Typing in TypeScript
TypeScript allows for dynamic typing where the type of a variable can be inferred from its value, making it easier to write code without explicitly defining types.
Example: Inferred Typing
var num = 2; // type inferred as number
console.log("value of num: " + num);
num = "12"; // Error: Cannot assign a string to a number
console.log(num);
Output:
error TS2011: Cannot convert 'string' to 'number'.
🔒 TypeScript Variable Scope
The scope of a variable defines where it can be accessed within your program. TypeScript has the following variable scopes:
- Global Scope: Variables declared outside any class or function. Accessible from anywhere in the code.
- Class Scope: Variables declared within a class but outside methods. Can be accessed via the class object.
- Local Scope: Variables declared inside a method or block. Accessible only within that method/block.
📚 Example: Variable Scope
var global_num = 12; // global variable
class Numbers {
num_val = 13; // class variable
static sval = 10; // static variable
storeNum(): void {
var local_num = 14; // local variable
}
}
console.log("Global num: " + global_num); // accessible
console.log(Numbers.sval); // static variable accessible
var obj = new Numbers();
console.log("Class num_val: " + obj.num_val); // accessible via object
Generated JavaScript:
var global_num = 12;
var Numbers = (function () {
function Numbers() {
this.num_val = 13; // class variable
}
Numbers.prototype.storeNum = function () {
var local_num = 14; // local variable
};
Numbers.sval = 10; // static field
return Numbers;
}());
console.log("Global num: " + global_num);
console.log(Numbers.sval);
var obj = new Numbers();
console.log("Class num_val: " + obj.num_val);
Output:
Global num: 12
10
Class num_val: 13
Note: Accessing a local variable outside its method results in an error:
error TS2095: Could not find symbol 'local_num'.
