Typescript variables
Created By: chatGPT
In TypeScript, variables can be declared using
let
, const
, or var
. Each has its own use case and scope rules. let and const are preferred in modern TypeScript for variable declarations due to their block scope.let name: string = 'John';
const age: number = 30;
var isActive: boolean = true;
Using
let
allows you to reassign the variable later, while const
creates an immutable reference to the variable. If you need to change the value, you will need to use let
instead.let score: number = 10;
score = 20; // This is valid
const pi: number = 3.14;
pi = 3.15; // This will cause an error
You can also declare multiple variables in a single line, which can help in initializing them efficiently. Additionally, you can declare a variable without assigning a value. In this case, it will have the type
undefined
until it's assigned.let x: number, y: string;
x = 5;
y = 'Hello';
let z: boolean;
// z is currently undefined
TypeScript supports type annotations, allowing you to specify the type of a variable explicitly. This helps in catching errors at compile time. You can annotate basic types as well as complex types like arrays or objects.
let numbers: number[] = [1, 2, 3];
let person: { name: string; age: number; } = { name: 'Jane', age: 25 };
When working with dynamic types, you can use the
any
type to tell TypeScript that the variable can hold any data type. However, this should be used sparingly as it can lead to less type safety.let data: any;
data = 'Hello';
data = 100; // Still valid