0
0
Typescriptprogramming~15 mins

Indexed access types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Indexed Access Types in TypeScript
📖 Scenario: Imagine you have a list of products in an online store. Each product has details like name, price, and category. You want to create a new variable that holds the type of the product's price using TypeScript's indexed access types.
🎯 Goal: Learn how to use indexed access types in TypeScript to extract the type of a specific property from an object type.
📋 What You'll Learn
Create an interface called Product with properties name, price, and category.
Create a type alias called PriceType that uses indexed access types to get the type of the price property from Product.
Create a variable called productPrice of type PriceType and assign it a value.
Print the value of productPrice.
💡 Why This Matters
🌍 Real World
Indexed access types help you reuse types from existing objects without repeating type definitions. This keeps your code consistent and easier to maintain.
💼 Career
Understanding indexed access types is useful for TypeScript developers working on large codebases where types are shared and reused across different parts of an application.
Progress0 / 4 steps
1
Create the Product interface
Create an interface called Product with these exact properties and types: name as string, price as number, and category as string.
Typescript
Need a hint?

Use the interface keyword to define the structure of a product object.

2
Create the PriceType using indexed access type
Create a type alias called PriceType that uses indexed access types to get the type of the price property from the Product interface.
Typescript
Need a hint?

Use type PriceType = Product["price"]; to get the type of the price property.

3
Create a variable with the PriceType
Create a variable called productPrice of type PriceType and assign it the value 29.99.
Typescript
Need a hint?

Declare productPrice with the type PriceType and assign the number 29.99.

4
Print the productPrice value
Write a console.log statement to print the value of productPrice.
Typescript
Need a hint?

Use console.log(productPrice); to show the value in the console.