0
0
Typescriptprogramming~15 mins

Default generic types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Default Generic Types in TypeScript
📖 Scenario: Imagine you are creating a simple container that can hold a value of any type. Sometimes, you want it to hold a string by default if no type is specified.
🎯 Goal: Build a generic Box type with a default type of string. Then create boxes with and without specifying the type.
📋 What You'll Learn
Create a generic type called Box with a default type parameter T = string
Create a variable stringBox of type Box without specifying the type parameter
Create a variable numberBox of type Box<number> specifying the type parameter
Assign appropriate values to stringBox and numberBox
Print the values of stringBox and numberBox
💡 Why This Matters
🌍 Real World
Default generic types help create flexible and reusable code components that work well with common default types, reducing the need to always specify types explicitly.
💼 Career
Understanding default generic types is useful for writing clean, maintainable TypeScript code in professional software development, especially in libraries and frameworks.
Progress0 / 4 steps
1
Create the generic Box type with default string
Create a generic type called Box with a type parameter T that defaults to string. It should have one property value of type T.
Typescript
Need a hint?

Use type Box<T = string> = { value: T } to set a default generic type.

2
Create stringBox and numberBox variables
Create a variable called stringBox of type Box without specifying the type parameter. Also create a variable called numberBox of type Box<number> specifying the type parameter.
Typescript
Need a hint?

Declare stringBox as Box and numberBox as Box<number>.

3
Assign values to stringBox and numberBox
Assign the string 'hello' to stringBox.value and the number 42 to numberBox.value.
Typescript
Need a hint?

Assign objects with value properties matching the types.

4
Print the values of stringBox and numberBox
Write two console.log statements to print stringBox.value and numberBox.value.
Typescript
Need a hint?

Use console.log(stringBox.value) and console.log(numberBox.value).