0
0
Typescriptprogramming~15 mins

Typeof operator in type context in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Typeof Operator in Type Context
📖 Scenario: Imagine you are building a simple program to store information about a product. You want to make sure the types of your variables match exactly, so you use TypeScript's typeof operator in a type context to keep your code safe and clear.
🎯 Goal: You will create a variable with product details, then use the typeof operator to create a type based on that variable. Finally, you will declare another variable using that type and print its value.
📋 What You'll Learn
Create a variable called product with exact properties: name as a string and price as a number
Create a type called ProductType using typeof product
Create a variable called newProduct of type ProductType with exact values
Print the newProduct variable
💡 Why This Matters
🌍 Real World
Using <code>typeof</code> in type contexts helps keep your code consistent and safe by reusing types from existing variables. This is useful when working with complex data structures or APIs.
💼 Career
Many TypeScript jobs require understanding how to create and reuse types efficiently. Using <code>typeof</code> in type contexts is a common technique to reduce errors and improve code maintainability.
Progress0 / 4 steps
1
Create the product variable
Create a variable called product with the exact properties: name set to "Book" and price set to 15.
Typescript
Need a hint?

Use const product = { name: "Book", price: 15 }; to create the variable.

2
Create the ProductType type using typeof
Create a type called ProductType using typeof product.
Typescript
Need a hint?

Use type ProductType = typeof product; to create the type.

3
Create a newProduct variable of type ProductType
Create a variable called newProduct of type ProductType with name set to "Pen" and price set to 5.
Typescript
Need a hint?

Use const newProduct: ProductType = { name: "Pen", price: 5 }; to create the variable.

4
Print the newProduct variable
Write a console.log statement to print the newProduct variable.
Typescript
Need a hint?

Use console.log(newProduct); to print the variable.