📖 Scenario: Imagine you run a small library. You want to keep track of different types of items like books and magazines. Each item has a title and an ID, but other details differ. You want a way to describe these items clearly in your program so you can manage them easily.
🎯 Goal: You will create a generic interface in TypeScript that can describe any library item type. Then you will use it to make specific types for books and magazines. This helps you write clear and reusable code.
📋 What You'll Learn
Create a generic interface called LibraryItem with a type parameter T.
The interface must have properties id (number), title (string), and details of type T.
Create a type BookDetails with properties author (string) and pages (number).
Create a type MagazineDetails with properties issue (number) and month (string).
Create a variable myBook of type LibraryItem<BookDetails> with example values.
Create a variable myMagazine of type LibraryItem<MagazineDetails> with example values.
Print myBook and myMagazine to the console.
💡 Why This Matters
🌍 Real World
Libraries, stores, or any inventory system often have many item types with shared and unique details. Generic interfaces help manage these cleanly.
💼 Career
Understanding generics is important for writing flexible and maintainable TypeScript code, a skill valued in many software development jobs.
Progress0 / 4 steps
1
Create the generic interface LibraryItem
Create a generic interface called LibraryItem with a type parameter T. It should have three properties: id of type number, title of type string, and details of type T.
Typescript
Hint
Use interface LibraryItem<T> and define the three properties inside.
2
Create types for book and magazine details
Create a type called BookDetails with properties author (string) and pages (number). Also create a type called MagazineDetails with properties issue (number) and month (string).
Typescript
Hint
Use type BookDetails = { author: string; pages: number; } and similarly for MagazineDetails.
3
Create variables using the generic interface
Create a variable called myBook of type LibraryItem<BookDetails> with id 1, title "The TypeScript Guide", and details with author "Jane Doe" and pages 250. Also create a variable called myMagazine of type LibraryItem<MagazineDetails> with id 2, title "Tech Monthly", and details with issue 45 and month "June".
Typescript
Hint
Use const myBook: LibraryItem<BookDetails> = { ... } and fill in the properties exactly.
4
Print the variables to the console
Write two console.log statements to print myBook and myMagazine to the console.
Typescript
Hint
Use console.log(myBook) and console.log(myMagazine) to show the objects.
Practice
(1/5)
1. What is the main benefit of using generic interfaces in TypeScript?
easy
A. They automatically generate user interfaces.
B. They make the code run faster at runtime.
C. They allow the same interface to work with different data types.
D. They replace the need for classes.
Solution
Step 1: Understand what generic interfaces do
Generic interfaces let you define a structure that can work with any type, not just one fixed type.
Step 2: Identify the benefit
This flexibility means you can reuse the same interface for different data types, making your code more flexible and reusable.
Final Answer:
They allow the same interface to work with different data types. -> Option C
Quick Check:
Generic interfaces = flexible types [OK]
Hint: Generic interfaces = one interface, many types [OK]
Common Mistakes:
Thinking generics improve runtime speed
Confusing generics with UI generation
Believing generics replace classes
2. Which of the following is the correct syntax to declare a generic interface named Box with a type parameter T?
easy
A. interface Box { content: T; }
B. interface Box<T> { content: T; }
C. interface Box<T> { content: any; }
D. interface Box<T> content: T;
Solution
Step 1: Recall generic interface syntax
Generic interfaces use angle brackets after the name to declare type parameters, like interface Name<T>.
Step 2: Check the property type
The property should use the generic type parameter T to be flexible.
Final Answer:
interface Box<T> { content: T; } -> Option B
Quick Check:
Generic syntax = interface Name<T> { prop: T } [OK]
Hint: Generic interfaces use <T> after name [OK]
Common Mistakes:
Omitting <T> after interface name
Using any instead of generic type
Missing curly braces or semicolons
3. What will be the output of this TypeScript code?
The interface Pair<T> requires a type argument when used, like Pair<number>.
Step 2: Identify the error in the code
The variable pair is declared as Pair without specifying <T>, causing a TypeScript error.
Final Answer:
Missing type argument when using Pair -> Option D
Quick Check:
Generic interfaces need type arguments [OK]
Hint: Always specify type argument when using generic interfaces [OK]
Common Mistakes:
Omitting the generic type argument
Trying to mix types without union
Assuming interface limits property count
5. Given this generic interface and usage, what is the best way to ensure the data property can hold either a string or an array of strings without losing type safety?
interface Response<T> {
data: T;
}
const response1: Response<string> = { data: 'hello' };
const response2: Response = { data: ['hello', 'world'] };
// How to declare a variable that can hold either response1 or response2?
hard
A. Use a union type: Response
B. Use any type: Response<any>
C. Create two separate interfaces for string and string[]
D. Use Response<object> to cover both
Solution
Step 1: Understand the need for flexible but safe typing
We want a variable that can hold either a string or an array of strings, keeping type safety.
Step 2: Use union types with generics
Declaring Response<string | string[]> allows data to be either type safely.
Final Answer:
Use a union type: Response<string | string[]> -> Option A
Quick Check:
Union types + generics = flexible and safe [OK]
Hint: Use union types inside generics for multiple allowed types [OK]
Common Mistakes:
Using any loses type safety
Creating duplicate interfaces wastes code
Using object is too broad and unsafe
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.