Variables in TypeScript



In this tutorial, we will learn about variables in TypeScript. We will cover the basics of declaring and using variables, including naming conventions.


What are Variables

Variables in TypeScript are used to store data values that can be manipulated during program execution. TypeScript is a statically typed language, meaning the data type of a variable is known at compile time.


Naming Variables

When naming variables in TypeScript, follow these conventions:

  • Variable names must start with a letter, underscore (_), or dollar sign ($).
  • Subsequent characters can include letters, digits, underscores, or dollar signs.
  • Variable names are case-sensitive.
  • Avoid using reserved keywords as variable names.
  • Use camelCase or snake_case naming conventions for readability.

Syntax

The syntax to declare variables in TypeScript is:

let variableName: DataType = value;
const variableName: DataType = value;


Example 1: Variable storing Integer Value

  1. Declare an integer variable named num using let.
  2. Assign a value of 10 to the variable.
  3. Print the value of the variable.

TypeScript Program

let num: number = 10;
console.log(`The value of num is: ${num}`);

Output

The value of num is: 10


Example 2: Variable storing String Value

  1. Declare a string variable named name using let.
  2. Assign the value 'John' to the variable.
  3. Print the value of the variable.

TypeScript Program

let name: string = 'John';
console.log(`The value of name is: ${name}`);

Output

The value of name is: John


Example 3: Variable storing Boolean Value

  1. Declare a boolean variable named isTrue using const.
  2. Assign the value true to the variable.
  3. Print the value of the variable.

TypeScript Program

const isTrue: boolean = true;
console.log(`The value of isTrue is: ${isTrue}`);

Output

The value of isTrue is: true