Skip to main content

Variables & Data Types in TypeScript (Live Playground)

In this tutorial, we will explore variables and data types in TypeScript. Understanding how to declare variables and specify their data types is crucial for writing clean, maintainable, and type-safe TypeScript code.

Variables

In TypeScript, you can declare variables using the let and const keywords:

  • let: Use let to declare variables that can be reassigned later.
  • const: Use const to declare variables that cannot be reassigned after their initial assignment. Here's an example of using let and const:
TypeScript
let age: number = 25;
const message: string = 'Hello, TypeScript!';

Data Types

TypeScript provides several built-in data types, which we will cover below:

1. number

The number data type is used for both integers and floating-point numbers:

TypeScript
let age: number = 25;
let pi: number = 3.14159;

2. string

The string data type represents textual data:

TypeScript
let message: string = 'Hello, TypeScript!';
let firstName: string = 'John';
let lastName: string = 'Doe';

3. boolean

The boolean data type represents true or false values:

TypeScript
let isStudent: boolean = true;
let hasGraduated: boolean = false;

4. array

To declare an array, use the Array type followed by the element type in angle brackets, or use the element type followed by square brackets:

TypeScript
let numbers: Array<number> = [1, 2, 3];
let names: string[] = ['Alice', 'Bob', 'Charlie'];

5. tuple

Tuples are fixed-length arrays with known, but potentially different, types:

TypeScript
let person: [string, number] = ['John Doe', 30];

6. enum

Enums are a way to define named constants for numeric values:

TypeScript
enum Color {
Red,
Green,
Blue,
}

let favoriteColor: Color = Color.Green;

7. any

The any data type represents any JavaScript value, effectively opting out of type checking for a variable:

TypeScript
let dynamicValue: any = 'Hello';
dynamicValue = 42;

8. void

The void data type is used to indicate that a function does not return any value:

TypeScript
function logMessage(message: string): void {
console.log(message);
}
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have explored variables and data types in TypeScript. Understanding how to declare variables with appropriate data types and type annotations is essential for writing clean, maintainable, and type-safe TypeScript code. In the upcoming tutorials, we will dive deeper into other TypeScript concepts and features, such as functions, classes, interfaces, and more.