Variables and constants are fundamental building blocks in any programming language. They are used to store values that can be used throughout your code.
Declaring Variables
To declare a variable in TypeScript, use the let
keyword followed by the variable name:
let myVariable: string;
In this example, we’re declaring a variable named myVariable
with the type of string
. This means that myVariable
can only hold string values.
You can also assign a value to the variable when you declare it:
let myVariable: string = "Hello, world!";
This assigns the string “Hello, world!” to myVariable
.
Declaring Constants
Constants are similar to variables, but their value cannot be changed once they are assigned. To declare a constant in TypeScript, use the const
keyword:
const myConstant: number = 42;
In this example, we’re declaring a constant named myConstant
with a value of 42
. Once a value has been assigned to myConstant
, it cannot be changed.
Using Variables and Constants
Once you’ve declared a variable or constant, you can use it throughout your code. For example:
let myVariable: string = "Hello, world!";
console.log(myVariable);
This will output “Hello, world!” to the console.
You can also assign a new value to a variable:
let myVariable: string = "Hello, world!";
myVariable = "Goodbye, world!";
console.log(myVariable);
This will output “Goodbye, world!” to the console.
Type Inference
TypeScript has a feature called type inference that can automatically determine the type of a variable based on its initial value. For example:
let myVariable = "Hello, world!";
In this example, TypeScript infers that myVariable
is a string because it’s assigned a string value.
Conclusion
Variables and constants are essential concepts in TypeScript. They allow you to store values that can be used throughout your code. By using the let
and const
keywords, you can declare variables and constants in TypeScript, and use them to write more powerful and expressive programs.