0
0
Typescriptprogramming~3 mins

Why Indexed access types in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could ask your code to tell you exactly what type a property has, without guessing or repeating yourself?

The Scenario

Imagine you have a big box of different toys, and you want to pick a specific toy by its label every time. Without a clear way to look up the toy by its label, you have to search through the whole box manually each time.

The Problem

Manually checking each toy's label is slow and can lead to mistakes, like picking the wrong toy or forgetting which labels exist. It's hard to keep track and easy to get confused when the box gets bigger.

The Solution

Indexed access types let you directly ask for the type of a specific property inside an object type by using its key. This means you can quickly and safely get the exact type you want without guessing or repeating yourself.

Before vs After
Before
type User = { name: string; age: number };
type UserName = string; // manually repeating the type
After
type User = { name: string; age: number };
type UserName = User['name']; // directly gets the type of 'name'
What It Enables

It makes your code smarter and safer by letting you reuse and check types automatically based on existing structures.

Real Life Example

When building a form, you can use indexed access types to ensure the input fields match the exact data types defined in your user profile, avoiding mistakes and extra work.

Key Takeaways

Manual type repetition is slow and error-prone.

Indexed access types let you get property types directly from objects.

This keeps your code clean, safe, and easy to maintain.