Skip to main content

Command Palette

Search for a command to run...

DAY 67: Mastering TypeScript Basics - Arrays, Tuples, Objects, and Enums | TypeScript

Published
9 min read
DAY 67: Mastering TypeScript Basics - Arrays, Tuples, Objects, and Enums | TypeScript
R

👨‍💻 Aspiring Software Developer | MERN Stack Developer.🚀 Documenting my journey in Full-Stack Development & DSA with Java.📘 Focused on writing clean code, building real-world projects, and continuous learning.


🚀 Introduction

Welcome to Day 67 of my Web Development Journey!
After mastering ReactJS along with popular state management tools like Zustand, Redux Toolkit, and RTK Query, I’ve now started learning TypeScript to further strengthen my frontend skills.

Over the past few days, I’ve focused on mastering the basics of TypeScript, including Basic Types, Arrays & Tuples, Type Aliases, Literal Types, Objects, and Enums.

📂 You can check out my TypeScript learning repository.

👉 I also share real-time updates and coding insights on Twitter.

I’m documenting this journey to stay consistent and share my learnings. Whether you’re starting with React or exploring TypeScript, I hope this blog gives you practical insights!

📅 Here’s What I Covered Over the Last 3 Days

Day 64

  • Introduction to TypeScript
  • Basic Types

Day 65

  • Arrays & Tuples
  • Type Aliases
  • Literal Types

Day 66

  • Objects
  • Enums

Let's explore each TypeScript concept in detail, with explanations and practical code examples 👇


1. TypeScript

TypeScript (TS) is a superset of JavaScript developed by Microsoft.
It adds static typing and additional features on top of JavaScript, making it easier to catch errors during development rather than at runtime.

In simple words:

  • Every valid JavaScript program is also a valid TypeScript program.
  • But with TypeScript, you can define types for variables, function parameters, objects, arrays, and more.

Why TypeScript?

  • Early Error Detection: Prevents bugs by catching type-related issues before execution.
  • Code Readability: Self-documenting through explicit types.
  • Scalability: Makes large codebases more manageable.
  • Tooling Support: Works seamlessly with modern editors (like VS Code) with autocomplete & IntelliSense.

Example

Here’s a quick comparison of JavaScript vs. TypeScript:

JavaScript (no type checking):

function add(a, b) {
  return a + b;
}

console.log(add(5, "10")); // Output: "510" (unexpected behavior)

TypeScript (with type checking):

function add(a: number, b: number): number {
  return a + b;
}

console.log(add(5, 10));   // Output: 15
console.log(add(5, "10"));  // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
  • TypeScript makes your JavaScript code safer, more predictable, and easier to scale.
  • It doesn’t replace JavaScript but compiles down to plain JS, which runs everywhere JavaScript does.

2. Basic Types in TypeScript

TypeScript extends JavaScript by adding static typing, which allows you to explicitly define the type of variables, function parameters, and return values.
Here are the most common basic types:

2.1 String

Represents textual data.

let username: string = "Ritik";
console.log(username); // Output: Ritik

2.2 Number

Represents integers and floating-point numbers.

let age: number = 21;
let pi: number = 3.14;
console.log(age, pi); // Output: 21 3.14

2.3 Boolean

Represents logical values: true or false.

let isLoggedIn: boolean = true;
console.log(isLoggedIn); // Output: true

2.4 Null & Undefined

Used when a variable has no value.

let emptyValue: null = null;
let notAssigned: undefined = undefined;

2.5 Any

Disables type checking — the variable can hold any type.
Use sparingly as it removes TypeScript’s type-safety.

let randomValue: any = "Hello";
randomValue = 42;
randomValue = true;

2.6 Union Types

A variable can hold more than one type.

let id: string | number;
id = 101;      // valid
id = "abc123"; // valid

2.7 Void

Represents functions that don’t return any value.

function greet(): void {
  console.log("Hello, TypeScript!");
}

2.8 Never

Represents a value that never occurs.
Used for functions that throw errors or run infinitely.

function throwError(message: string): never {
  throw new Error(message);
}

2.9 Summary

  • string, number, boolean → Core primitive types.
  • null & undefined → Represent empty/unassigned values.
  • any → Accepts all types, but reduces type safety.
  • union types → Allow flexibility with multiple types.
  • void & never → Used for functions with no return or unreachable code.

3. Arrays in TypeScript

Arrays in TypeScript work similarly to JavaScript arrays but with type safety.
You can define the type of elements an array can hold, ensuring that only those types are allowed.

Syntax:

let arr: number[] = [1, 2, 3];   // Array of numbers
let fruits: string[] = ["apple", "banana", "mango"]; // Array of strings

Generic Array Syntax:

TypeScript also supports generics for arrays

let arr: Array<number> = [10, 20, 30];
let names: Array<string> = ["John", "Doe", "Alice"];

Mixed / Union Type Arrays:

We can use union types to allow multiple types in an array

let mixed: (string | number)[] = ["hello", 42, "world", 100];

Multidimensional Arrays:

Arrays can also be nested

let matrix: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
];

Example:

let scores: number[] = [90, 85, 100];
scores.push(75);   // Valid
// scores.push("hi");   // Error: Argument of type 'string' is not assignable to 'number'
  • Arrays in TypeScript provide type safety.
  • We can use simple type arrays, generics, union types, and multidimensional arrays.
  • TypeScript prevents invalid elements from being added.

4. Tuples in TypeScript

A tuple is a special type of array in TypeScript where the number of elements is fixed and the types of elements are known.
It allows us to store a collection of values with different types in a specific order.

Example: Basic Tuple

let user: [string, number];  
user = ["Alice", 25];    // valid  
// user = [25, "Alice"];   // invalid (wrong order of types)

Example: Tuple with Optional Elements

let person: [string, number?, boolean?];  
person = ["Bob"];                // valid  
person = ["Bob", 30];          // valid  
person = ["Bob", 30, true];  // valid

Example: Tuple with Rest Elements

let scores: [string, ...number[]];  
scores = ["Math", 90, 85, 100];   // first element string, rest numbers
  • Tuples allow fixed-length arrays with defined types.
  • They are useful when the order and type of elements matter (e.g., coordinates, key-value pairs).
  • With optional and rest elements, tuples become more flexible.

5. Type Aliases

Type Aliases in TypeScript allow us to create custom names for types.
They make code more readable, reusable, and easier to maintain.

Instead of repeating complex types across your codebase, you can define them once and reuse them.

Example:

// Defining a type alias for a union type
type ID = number | string;

let userId: ID;
userId = 101;      // valid
userId = "abc";  // valid

// Defining a type alias for an object
type User = {
  id: number;
  name: string;
  isActive: boolean;
};

const user1: User = {
  id: 1,
  name: "Ritik",
  isActive: true
};
  • Type Aliases let us give a name to a type, making code more readable.
  • They can represent primitives, objects, functions, or union types.
  • Useful for avoiding repetition and improving code maintainability.

6. Literal Types in TypeScript

In TypeScript, literal types let us specify exact values a variable can hold instead of just general types.
This provides more precision and restricts the variable to a fixed set of values.

For example, instead of declaring a variable as just a string, you can restrict it to specific strings like "success" | "error".

Example:

// String Literal Type
let status: "success" | "error" | "pending";
status = "success";   // Valid
status = "error";        // Valid
// status = "failed";   // Error: not allowed

// Number Literal Type
let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 4;      // Valid
// diceRoll = 7;  // Error: not allowed

// Boolean Literal Type
let isActive: true;
isActive = true;      // Valid
// isActive = false; // Error
  • Literal Types restrict a variable to specific values.
  • They are often combined with union types to enforce strict choices.
  • Commonly used in cases like status codes, configuration values, or enums.

7. Objects in TypeScript

In TypeScript, objects are collections of key-value pairs where each property has a defined type.
Unlike plain JavaScript objects, TypeScript ensures that only the specified properties with correct types are allowed.

With type aliases, we can make object structures reusable, readable, and easier to maintain.

Example:

// Basic object type with type alias
type Person = {
  name: string;
  age: number;
};

let person: Person = {
  name: "Ritik",
  age: 22,
};

// Optional properties
type User = {
  id: number;
  username: string;
  email?: string; // optional property
};

let user: User = {
  id: 1,
  username: "ritik_dev",
};

// Readonly properties
type Car = {
  readonly brand: string;
  model: string;
};

let car: Car = { brand: "Tesla", model: "Model 3" };
// car.brand = "BMW";  Error: brand is readonly

Key Features:

  • Optional properties (?) → Not required in the object.
  • Readonly properties → Cannot be reassigned after initialization.
  • Nested objects → Objects can contain other objects.
  • Type Aliases → Define reusable object structures.
// Nested object with type alias
type Address = {
  city: string;
  zip: number;
};

type Employee = {
  id: number;
  name: string;
  address: Address;
};

let emp: Employee = {
  id: 101,
  name: "John",
  address: {
    city: "Delhi",
    zip: 110001,
  },
};
  • Objects in TypeScript are strongly typed, preventing invalid properties.
  • Use optional (?) and readonly modifiers for more control.
  • Define object structures using type aliases for better reusability.

8. Enums

Enums in TypeScript allow you to define a set of named constants, making code more readable and meaningful.
They are useful when you have a fixed set of related values, like directions, status codes, or user roles.

Example:

// Numeric enum (default starts from 0)
enum Direction {
  Up,
  Down,
  Left,
  Right,
}

let move: Direction = Direction.Up;

// String enum
enum Status {
  Pending = "PENDING",
  InProgress = "IN_PROGRESS",
  Completed = "COMPLETED",
}

let taskStatus: Status = Status.Pending;

Key Features:

  • Numeric and string enums supported.
  • Improves code readability instead of using raw numbers or strings.
  • Can be used for flags or grouped constant values.

9. What’s Next

I’m excited to keep growing and sharing along the way! Here’s what’s coming up:

  • Posting new blog updates every 3 days to share what I’m learning and building.
  • Diving deeper into Data Structures & Algorithms with Java — check out my ongoing DSA Journey Blog for detailed walkthroughs and solutions.
  • Sharing regular progress and insights on X (Twitter) — feel free to follow me there and join the conversation!

Thanks for being part of this journey!


10. Conclusion

Over the past few days, I’ve laid a solid foundation in TypeScript, exploring its key features and capabilities for building safer and more maintainable frontend applications.

Here’s a quick recap of what I learned:

  • Basic Types: Strong typing for primitives like string, number, boolean, null, undefined, any, union, void, and never.
  • Arrays & Tuples: Type-safe collections with fixed-length or flexible structures.
  • Type Aliases: Reusable names for complex types to improve readability and maintainability.
  • Literal Types: Restrict variables to specific values for stricter control.
  • Objects: Strongly typed objects with optional, readonly, and nested properties, using type aliases for structure.
  • Enums: Named constants for readable and meaningful values.

By understanding these TypeScript fundamentals, my React projects will become more robust, predictable, and scalable.

This marks the beginning of my journey into typed JavaScript, and I’m excited to apply these concepts in real-world projects.

📂 You can explore all my TypeScript experiments in my learning repository.

I’ll continue sharing updates and insights on Twitter. Whether you’re starting with TypeScript or looking to strengthen your frontend skills, I hope this blog provides useful guidance and inspiration!

More from this blog

Full Stack Development Logs

23 posts

I'm Ritik, a self-taught developer sharing my full stack web dev journey—daily learnings, projects, and insights as I grow into a full stack developer.