Hello, generic builder! In Module Six, you learned about inheritance and polymorphism. Now it is time to learn about generics β a powerful feature that makes your code more flexible and reusable.
Generics allow you to write code that works with many different types. Instead of writing the same code for strings, numbers, and other types, you write it once with generics.
In this module, you will learn how to use generics to create flexible functions, classes, and interfaces.
Let's start writing flexible code with generics!
By the end of this module, you will be able to:
In Lagos, a store owner named Mr. Okonkwo wanted to store different items in boxes. He had boxes for shoes, boxes for books, and boxes for clothes. Each box was different.
He thought, "Wouldn't it be great if I had one type of box that could hold anything?"
In programming, generics are like that universal box. They allow you to create a single class or function that can work with any type.
Definition: Generics are a way to write code that works with many different types.
Why is it important? They make your code flexible and reusable.
Simple explanation: Generics are like a template that can work with any type.
Real-life example: A container that can hold anything.
School example: A bag that can carry any subject books.
Home example: A drawer that can store different items.
Nigerian example: A vehicle that can carry any load.
function identity(value: T): T { return value; }
Mini summary: Generics work with many types.
Definition: A generic function is a function that works with any type.
Why is it important? It avoids code duplication.
Simple explanation: You write one function that works for all types.
Real-life example: A function that returns whatever you give it.
School example: A function that copies any data.
Home example: A function that stores any item.
Nigerian example: A function that processes any data.
function identity(value: T): T { return value; }
Mini summary: Generic functions work with any type.
Definition: A generic class is a class that works with any type.
Why is it important? It makes classes reusable.
Simple explanation: A class that can hold any type of data.
Real-life example: A box that can hold any item.
School example: A folder that can hold any document.
Home example: A container that can hold anything.
Nigerian example: A storage unit that can hold any goods.
class Box{ private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } }
Mini summary: Generic classes work with any type.
Definition: A generic interface is an interface that works with any type.
Why is it important? It makes interfaces flexible.
Simple explanation: An interface that can describe any type.
Real-life example: A blueprint for a container.
School example: A template for a document.
Home example: A design for a storage box.
Nigerian example: A plan for a shop.
interface GenericInterface{ value: T; getValue(): T; }
Mini summary: Generic interfaces work with any type.
Definition: You can use multiple type parameters in generics.
Why is it important? It allows more flexibility.
Simple explanation: You can work with two or more types.
Real-life example: A function that works with two different types.
School example: A function that takes a student and a grade.
Home example: A function that takes a person and a task.
Nigerian example: A function that takes a product and a price.
function pair(a: T, b: U): [T, U] { return [a, b]; }
Mini summary: Multiple type parameters add flexibility.
Definition: Constraints limit the types that can be used with generics.
Why is it important? They ensure that only certain types are used.
Simple explanation: You say "only types that have a specific property."
Real-life example: Only items that can be stacked.
School example: Only students who have an ID.
Home example: Only items that are fragile.
Nigerian example: Only products that have a barcode.
function getLength(value: T): number { return value.length; }
Mini summary: Constraints limit allowed types.
Definition: keyof constraint ensures a type is a key of an object.
Why is it important? It restricts types to keys of an object.
Simple explanation: You say "only keys that exist in the object."
Real-life example: Only valid property names.
School example: Only valid field names.
Home example: Only valid labels.
Nigerian example: Only valid product attributes.
function getProperty(obj: T, key: K): T[K] { return obj[key]; }
Mini summary: keyof restricts types to object keys.
Definition: Utility types are built-in generics in TypeScript.
Why is it important? They simplify common tasks.
Simple explanation: TypeScript provides useful generics for you.
Real-life example: Partial, Readonly, Pick.
School example: Partial for a student record.
Home example: Readonly for a family list.
Nigerian example: Pick for a product.
interface Customer {
name: string;
age: number;
email: string;
}
type PartialCustomer = Partial;
Mini summary: Utility types are built-in generics.
Definition: Arrays are generic in TypeScript.
Why is it important? You can have arrays of any type.
Simple explanation: An array of numbers or strings.
Real-life example: let numbers: number[] = [1, 2, 3];
School example: let grades: number[] = [90, 85, 88];
Home example: let names: string[] = ["Ada", "Chidi"];
Nigerian example: let cities: string[] = ["Lagos", "Abuja"];
function getFirst(items: T[]): T { return items[0]; }
Mini summary: Arrays are generic in TypeScript.
Definition: Promises are generic in TypeScript.
Why is it important? They know what type they resolve to.
Simple explanation: A promise can return any type.
Real-life example: let promise: Promise
School example: let promise: Promise
Home example: let promise: Promise
Nigerian example: let promise: Promise
function fetchData(): Promise{ return new Promise((resolve) => resolve("Data")); }
Mini summary: Promises are generic.
Definition: Common mistakes are errors that beginners often make with generics.
Why is it important? Avoiding them saves time and frustration.
Simple explanation: Don't forget to specify the type.
Real-life example: Using any instead of generic.
School example: Not using generics when needed.
Home example: Forgetting to use generics.
Nigerian example: Not using generics for flexibility.
// Avoid using any
function identity(value: any): any {
return value;
}
Mini summary: Avoid using any; use generics instead.
Definition: Best practices are the recommended ways to use generics.
Why is it important? They make your code clean and safe.
Simple explanation: Use generics for flexibility, but add constraints when needed.
Real-life example: Use generics for reusable code.
School example: Use generics for data structures.
Home example: Use generics for utilities.
Nigerian example: Use generics for business logic.
function identity(value: T): T { return value; }
Mini summary: Use generics for reusable, flexible code.
Definition: Generics are not just for code β they are everywhere in life.
Why is it important? It shows that generics are natural and easy to understand.
Simple explanation: A container that can hold anything.
Real-life example: A bag that carries books, food, or clothes.
School example: A folder that holds papers, drawings, or photos.
Home example: A drawer that stores tools, clothes, or toys.
Nigerian example: A vehicle that carries goods, people, or animals.
Generics are like containers that can hold anything.
Mini summary: Generics are natural and everywhere.
Definition: Type inference means TypeScript can guess the generic type.
Why is it important? It saves you from writing the type.
Simple explanation: TypeScript is smart β it can figure out the type.
Real-life example: identity(5) β TypeScript knows it's number.
School example: identity("Hello") β TypeScript knows it's string.
Home example: identity(true) β TypeScript knows it's boolean.
Nigerian example: identity("Lagos") β TypeScript knows it's string.
let result = identity(5); // TypeScript infers number
Mini summary: TypeScript can infer generic types.
Definition: You are now a generic master β you understand generics.
Why is it important? You can now write flexible, reusable code.
Simple explanation: You have mastered generics.
Real-life example: You can now write generic functions.
School example: You can use generics in school projects.
Home example: You can practice at home.
Nigerian example: You can build apps with generics in Nigeria.
Generic Master Checklist: - Writes generic functions - Creates generic classes - Uses constraints - Understands type inference - Uses generic utility types
Mini summary: You are now a generic master!
| Word | Simple Definition |
|---|---|
| Generic | Code that works with many types. |
| Type Parameter | A placeholder for a type. |
| Constraint | Limits allowed types. |
| Inference | TypeScript guesses the type. |
| Utility Type | Built-in generic type. |
| Partial | Makes all properties optional. |
| Readonly | Makes all properties read-only. |
| Pick | Selects specific properties. |
| keyof | Represents keys of an object. |
| Flexible | Able to change easily. |
function identity(value: T): T { return value; }
class Box{ private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } }
+-----------------------+-----------------------+ | Non-Generic | Generic | +-----------------------+-----------------------+ | Code duplication | Reusable code | | Less flexible | More flexible | | Specific to a type | Works with any type | | Harder to maintain | Easier to maintain | | More error-prone | More type-safe | +-----------------------+-----------------------+
| Type | Description | Example |
|---|---|---|
| T | Single type parameter | function identity |
| T, U | Multiple type parameters | function pair |
| extends | Constraint | function getLength |
| keyof | Key constraint | function getProperty |
| Utility | Description | Example |
|---|---|---|
| Partial | All properties optional | Partial |
| Readonly | All properties read-only | Readonly |
| Pick | Select specific properties | Pick |
| Record | Create a type with keys | Record |
(Included after each lesson above β review them!)
In this module, you learned about generics. You discovered how to write generic functions, classes, and interfaces. You also learned about constraints, multiple type parameters, and generic utility types. You are now a generic master. In the next module, you will learn about advanced types. Congratulations on completing Module Seven!
Match the term with its definition.
| Term | Definition |
|---|---|
| 1. Generic | A. Code that works with many types |
| 2. Type Parameter | B. Placeholder for a type |
| 3. Constraint | C. Limits allowed types |
| 4. Inference | D. TypeScript guesses the type |
| 5. Utility | E. Built-in generic type |
Answers: 1-A, 2-B, 3-C, 4-D, 5-E
βGeneric Designβ
In groups, design a generic class or function for a real-world scenario (like a container or a processor). Use generics to make it flexible. Share your design with the class.
βMy Generic Codeβ
Write a TypeScript program that uses generics. Include a generic function, a generic class, and a constraint. Share your code with the class.
βGeneric Libraryβ
Create a library of generic functions and classes for a business. Include functions for arrays, containers, and processors. Present your library to the class.
βWrite Generic Codeβ
Write a TypeScript program that uses generics. Include a generic function, a generic class, and a constraint. Compile and run it. Share your code and output.
βGeneric Challengeβ
Create a complex generic function or class that uses multiple type parameters, constraints, and utility types. Share your solution with the class.
(Answers to fill-in-the-blank, true/false, and multiple choice are provided within those sections.)
In Module Eight, you will learn about advanced types. To prepare:
Get ready to learn about advanced types!
End of Module Seven Β· You are now a generic master!