TypeScript Variables and Data types
- Declaring and Defining Variables:
— Declaration: `let variableName;` or `let variableName: dataType;`
— Definition: `variableName = value;` or `let variableName: dataType = value;`
— Example:
let age: number;
age = 25;
2. About “any”:
— `any` type allows you to assign any value to a variable, useful when the type is dynamic or uncertain.
— Example:
let dynamicValue: any = 5;
dynamicValue = "Hello";
3. ”var” Vs “let” keywords:
— `var` is function-scoped, while `let` is block-scoped.
— `let` is preferred over `var` for more predictable behavior.
— Example:
function example() {
if (true) {
var x = 5; // Function-scoped
let y = 10; // Block-scoped
}
console.log(x); // Works
console.log(y); // Error
}
4. Static and Dynamic Type:
— Static Typing: Types are known at compile time.
— Dynamic Typing: Types are determined at runtime.
— TypeScript is statically typed, but it allows dynamic typing with `any`.
— Example:
let staticVar: number = 5;
let dynamicVar: any = "Hello";
5. Data types:
String: Represents textual data.
let message: string = "Hello, TypeScript!";
- Number: Represents numeric data.
let count: number = 42;
- Array: Represents a collection of elements of the same type.
let numbers: number[] = [1, 2, 3, 4];
- Object: Represents a key-value pair collection.
let person: { name: string, age: number } = { name: "John", age: 25 };
- Tuple: Represents an array with fixed elements and types.
let personTuple: [string, number] = ["John", 25];
- Enum: Represents a set of named constant values.
enum Color { Red, Green, Blue };
let selectedColor: Color = Color.Red;
- Void: Represents the absence of a type. Typically used for functions that don’t return a value.
function logMessage(): void {
console.log("This is a log message");
}
- Null: Represents an intentional absence of any object value.
let nullValue: null = null;