Step 1 – Variables and Constants in TypeScript

What are Variables and Constants?

Variables and constants are like containers for holding data in your code. Just as in Java, where you use int, String, or double to store different types of values, TypeScript uses variables and constants to do the same thing but with added type safety.

Declaring Variables

To declare a variable in TypeScript, you use the let keyword, followed by the variable name. Think of let as Java’s var, but with type safety:

let myVariable: string;

In this example, myVariable is a container that can only hold strings. It’s like declaring a variable in Java with a specific type:

String myVariable;

You can also assign a value when declaring the variable:

let myVariable: string = "Hello, world!";

Here, myVariable is initialized with the string "Hello, world!". It’s similar to initializing a String variable in Java:

String myVariable = "Hello, world!";

Declaring Constants

Constants in TypeScript are like final variables in Java—once assigned, their value cannot be changed. Use the const keyword for constants:

const myConstant: number = 42;

In this example, myConstant is assigned the value 42 and cannot be modified. This is similar to a final variable in Java:

final int myConstant = 42;

Using Variables and Constants

Once declared, you can use variables and constants throughout your code. For instance:

let myVariable: string = "Hello, world!";
console.log(myVariable); // Outputs: Hello, world!

You can change the value of a variable but not a constant:

let myVariable: string = "Hello, world!";
myVariable = "Goodbye, world!";
console.log(myVariable); // Outputs: Goodbye, world!

const myConstant: number = 42;
// myConstant = 50; // Error: Cannot assign to 'myConstant' because it is a constant.

Type Inference

TypeScript can automatically figure out the type of a variable based on its initial value. This is called type inference and it works similarly to Java’s type inference in local variables:

let myVariable = "Hello, world!"; // TypeScript infers that myVariable is a string

In Java, local variables can also be inferred if the type is clear from the context:

var myVariable = "Hello, world!"; // Java infers that myVariable is a String

Conclusion

In TypeScript, variables and constants let you store and manage data in your code, similar to how you use them in Java. By using let for variables and const for constants, you can write code that is easier to understand and less prone to errors. TypeScript’s type system adds an extra layer of safety, helping you catch issues early and write more robust programs.

Leave a Reply

Your email address will not be published. Required fields are marked *