Structuring Data Safely - Textnotes

Structuring Data Safely


Learn how to define and use object types and type aliases in TypeScript. This module explains typing objects, using the type keyword, and working with nested object structures using practical examples.

1. Typing Objects

In TypeScript, objects can be typed by explicitly defining the shape of the object. This ensures that all required properties exist and have the correct types.

Basic Object Typing Example


let user: {
id: number;
name: string;
isActive: boolean;
};

user = {
id: 1,
name: "Muni",
isActive: true
};

If a property is missing or has the wrong type, TypeScript raises a compile-time error.

Optional Object Properties

Optional properties are defined using a question mark.


let employee: {
id: number;
name: string;
department?: string;
};

employee = {
id: 101,
name: "Ravi"
};

2. Using the Type Keyword

The type keyword allows you to create reusable custom types. This improves code readability and avoids repetition.

Defining a Type Alias


type User = {
id: number;
name: string;
email: string;
};

Using the Type Alias


let admin: User = {
id: 1,
name: "Muni",
email: "muni@example.com"
};

Type aliases are widely used in real-world applications, especially in APIs and shared models.

Type Aliases with Union Types


type Status = "active" | "inactive" | "blocked";

let userStatus: Status = "active";

This restricts the variable to specific allowed values.

3. Nested Object Structures

Nested objects are common in real-world applications such as API responses and configuration files. TypeScript allows you to type these structures accurately.

Nested Object Example


type Address = {
city: string;
state: string;
zipCode: number;
};

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

Using the Nested Object


let customer: Customer = {
id: 1001,
name: "Muni",
address: {
city: "Mumbai",
state: "MH",
zipCode: 400001
}
};

Deeply Nested Structure Example


type Order = {
orderId: number;
product: {
name: string;
price: number;
};
deliveryStatus: {
shipped: boolean;
delivered: boolean;
};
};

Nested typing helps prevent data mismatch and ensures predictable application behavior.

Conclusion

Object types and type aliases are fundamental to structuring data in TypeScript. They enforce consistency, improve code reuse, and make applications easier to maintain. Mastering these concepts is essential for building scalable, real-world TypeScript applications.