0
0
Typescriptprogramming~15 mins

Generic class syntax in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic class syntax
📖 Scenario: Imagine you want to create a box that can hold any type of item. This box should be able to store numbers, strings, or even objects. Using a generic class helps you build such a flexible box.
🎯 Goal: You will build a generic class called Box that can store one item of any type. Then, you will create a box for numbers and a box for strings, and finally print their contents.
📋 What You'll Learn
Create a generic class called Box with a type parameter T.
Add a property content of type T to the class.
Add a constructor that takes a parameter content of type T and assigns it to the property.
Create a variable numberBox of type Box<number> with content 123.
Create a variable stringBox of type Box<string> with content 'hello'.
Print the contents of numberBox and stringBox.
💡 Why This Matters
🌍 Real World
Generic classes let you write flexible and reusable code that works with many data types without repeating yourself.
💼 Career
Understanding generics is important for writing clean, type-safe code in TypeScript, which is widely used in web development jobs.
Progress0 / 4 steps
1
Create the generic class Box
Create a generic class called Box with a type parameter T. Inside the class, add a property called content of type T. Add a constructor that takes a parameter content of type T and assigns it to the property content.
Typescript
Need a hint?

Use class Box<T> to create a generic class. The constructor should assign the parameter to the property.

2
Create a numberBox with number content
Create a variable called numberBox of type Box<number> and set it to a new Box with the number 123 as content.
Typescript
Need a hint?

Use const numberBox: Box<number> = new Box(123); to create the box.

3
Create a stringBox with string content
Create a variable called stringBox of type Box<string> and set it to a new Box with the string 'hello' as content.
Typescript
Need a hint?

Use const stringBox: Box<string> = new Box('hello'); to create the box.

4
Print the contents of both boxes
Write two console.log statements to print the content of numberBox and stringBox.
Typescript
Need a hint?

Use console.log(numberBox.content); and console.log(stringBox.content); to print the values.