Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Certified Typescript Programming Expert Β· Lesson 8 of 16

Module Seven

πŸ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
8
Module 7 Β· Certified TypeScript Programming Expert Β· Beginners

πŸ“˜ Module Seven: Generics – Writing Flexible and Reusable Code


πŸ“– Module Introduction

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!


🎯 Learning Objectives

By the end of this module, you will be able to:

  • Understand what generics are.
  • Write generic functions.
  • Write generic classes.
  • Use constraints with generics.
  • Use generics with interfaces.

πŸ“š Warm-up Story: The Box That Fits Everything

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.


πŸ“˜ Main Lessons

Lesson 1: What are Generics?

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.

Lesson 2: Generic Functions

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.

Lesson 3: Generic Classes

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.

Lesson 4: Generic Interfaces

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.

Lesson 5: Multiple Type Parameters

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.

Lesson 6: Constraints

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.

Lesson 7: Keyof Constraint

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.

Lesson 8: Generic Utility Types

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.

Lesson 9: Using Generics with Arrays

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.

Lesson 10: Generics with Promises

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 = fetchData();

School example: let promise: Promise = getGrade();

Home example: let promise: Promise = checkStatus();

Nigerian example: let promise: Promise = getProduct();

   function fetchData(): Promise {
     return new Promise((resolve) => resolve("Data"));
   }

Mini summary: Promises are generic.

Lesson 11: Common Mistakes with Generics

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.

Lesson 12: Best Practices for Generics

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.

Lesson 13: Generics in Everyday Life

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.

Lesson 14: Generic Type Inference

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.

Lesson 15: You – The Generic Master

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!


πŸ“– Key Vocabulary

WordSimple Definition
GenericCode that works with many types.
Type ParameterA placeholder for a type.
ConstraintLimits allowed types.
InferenceTypeScript guesses the type.
Utility TypeBuilt-in generic type.
PartialMakes all properties optional.
ReadonlyMakes all properties read-only.
PickSelects specific properties.
keyofRepresents keys of an object.
FlexibleAble to change easily.

🧩 Important Concepts

  • Generics work with many types.
  • Generic functions and classes are reusable.
  • Constraints limit allowed types.
  • TypeScript can infer generic types.
  • You are now a generic master.

πŸ”’ Step-by-Step Explanations

How to Use Generics (in 4 steps)

  1. Step 1: Define a type parameter using angle brackets.
  2. Step 2: Use the type parameter in your function or class.
  3. Step 3: Add constraints if needed.
  4. Step 4: Use the generic function or class.

🌍 Real-life Examples

  • Container: A class that can hold any type.
  • Function: A function that works with any type.
  • Interface: An interface that describes any type.
  • Array: An array of any type.
  • Promise: A promise that resolves to any type.

πŸ‡³πŸ‡¬ Nigerian Examples

  • Container: A class that can hold any item.
  • Function: A function that processes any data.
  • Interface: An interface for any product.
  • Array: An array of any items.
  • Promise: A promise for any data.

🎈 Fun Examples Children Can Relate To

  • Box: A box that can hold any toy.
  • Bag: A bag that can carry any item.
  • Container: A container that can store anything.
  • Holder: A holder that can hold any object.
  • Wrapper: A wrapper that can wrap anything.

🏠 Everyday Examples

  • Drawer: A drawer that can store any item.
  • Box: A box that can hold anything.
  • Bag: A bag that can carry any load.
  • Container: A container for any type.
  • Storage: A storage unit for any item.

πŸ‘©β€πŸ« Teacher Notes

  • This module is about generics – keep it simple and practical.
  • Use many examples to illustrate each concept.
  • Encourage students to write generic code.
  • Emphasise the importance of flexibility and reusability.
  • Make it interactive with live coding.

πŸ‘ͺ Parent Tips

  • Encourage your child to think about generics in everyday life.
  • Help them understand the concept of containers and reusability.
  • Support their coding practice.
  • Discuss how generics make code more flexible.
  • Celebrate their progress.

πŸ’‘ Interesting Facts

  • Generics are a feature in many languages, including Java and C#.
  • Generics were introduced in TypeScript to add flexibility.
  • TypeScript's generics are similar to those in Java.
  • Generics help with type safety.
  • Generics are used in many libraries.

πŸ€” Did You Know?

  • Did you know that generics are also called polymorphic types?
  • Did you know that TypeScript can infer generic types?
  • Did you know that generics are used in React?
  • Did you know that generics help avoid code duplication?

🧠 Remember This

  • Generics work with many types.
  • Generic functions and classes are reusable.
  • Constraints limit allowed types.
  • TypeScript can infer generic types.
  • You are a generic master.

⚠️ Common Mistakes

  • Mistake 1: Using any instead of generics.
  • Mistake 2: Not using constraints when needed.
  • Mistake 3: Not using type inference.
  • Mistake 4: Using generics when not needed.
  • Mistake 5: Not using generic utility types.

βœ… Best Practices

  • Always use generics for reusable code.
  • Always use constraints when needed.
  • Always let TypeScript infer types.
  • Always use generics with arrays and promises.
  • Always use generic utility types.

🎨 ASCII Illustrations

Generic Function – Example

   function identity(value: T): T {
     return value;
   }

Generic Class – Example

   class Box {
     private value: T;
     constructor(value: T) {
       this.value = value;
     }
     getValue(): T {
       return this.value;
     }
   }

Comparison: Generic vs Non-Generic

   +-----------------------+-----------------------+
   |  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        |
   +-----------------------+-----------------------+

πŸ“Š Comparison Tables

Generic Types

TypeDescriptionExample
TSingle type parameterfunction identity(value: T): T
T, UMultiple type parametersfunction pair(a: T, b: U)
extendsConstraintfunction getLength
keyofKey constraintfunction getProperty

Utility Types

UtilityDescriptionExample
PartialAll properties optionalPartial
ReadonlyAll properties read-onlyReadonly
PickSelect specific propertiesPick
RecordCreate a type with keysRecord

πŸ“ Summary After Every Lesson

(Included after each lesson above – review them!)


πŸ“Œ End-of-Module Summary

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!


❓ Frequently Asked Questions

  1. What are generics? Code that works with many types.
  2. Why use generics? For flexibility and reusability.
  3. What is a type parameter? A placeholder for a type.
  4. What is a constraint? Limits allowed types.
  5. What is type inference? TypeScript guesses the type.
  6. What are utility types? Built-in generics.
  7. What is Partial? Makes properties optional.
  8. What is Readonly? Makes properties read-only.
  9. What is Pick? Selects specific properties.
  10. What is keyof? Represents keys of an object.

πŸ“ Review Questions (15)

  1. What are generics?
  2. Why are generics useful?
  3. What is a type parameter?
  4. How do you write a generic function?
  5. How do you write a generic class?
  6. What is a constraint?
  7. What is type inference?
  8. What are utility types?
  9. What is Partial?
  10. What is Readonly?
  11. What is Pick?
  12. What is keyof?
  13. What is a common mistake?
  14. What is a best practice?
  15. What makes you a generic master?

✏️ Fill-in-the-Blank Exercises

  1. __________ are code that works with many types.
  2. A __________ is a placeholder for a type.
  3. A __________ limits allowed types.
  4. __________ is when TypeScript guesses the type.
  5. __________ are built-in generics.
  6. __________ makes all properties optional.
  7. __________ makes all properties read-only.
  8. __________ selects specific properties.
  9. __________ represents keys of an object.
  10. You are a __________ master.

βœ… True or False Exercises

  1. Generics work with many types. (True)
  2. A type parameter is a placeholder for a type. (True)
  3. Constraints allow any type. (False)
  4. Type inference means TypeScript guesses the type. (True)
  5. Utility types are built-in generics. (True)
  6. Partial makes properties required. (False)
  7. Readonly makes properties read-only. (True)
  8. Pick selects specific properties. (True)
  9. keyof represents values of an object. (False)
  10. You are a generic master. (True)

πŸ”˜ Multiple Choice Questions (15 with answers)

  1. What are generics?
    a) Code that works with many types
    b) A game
    c) A video
    Answer: a
  2. What is a type parameter?
    a) A placeholder for a type
    b) A game
    c) A video
    Answer: a
  3. What is a constraint?
    a) Limits allowed types
    b) Allows any type
    c) A game
    Answer: a
  4. What is type inference?
    a) TypeScript guesses the type
    b) TypeScript deletes the type
    c) A game
    Answer: a
  5. What are utility types?
    a) Built-in generics
    b) A game
    c) A video
    Answer: a
  6. What does Partial do?
    a) Makes all properties optional
    b) Makes all properties required
    c) A game
    Answer: a
  7. What does Readonly do?
    a) Makes all properties read-only
    b) Makes all properties writable
    c) A game
    Answer: a
  8. What does Pick do?
    a) Selects specific properties
    b) Selects all properties
    c) A game
    Answer: a
  9. What is keyof?
    a) Represents keys of an object
    b) Represents values of an object
    c) A game
    Answer: a
  10. What is a common mistake?
    a) Using any instead of generics
    b) Using generics
    c) Using constraints
    Answer: a
  11. What is a best practice?
    a) Use generics for reusable code
    b) Use any
    c) Avoid generics
    Answer: a
  12. What is the purpose of generics?
    a) Reusability
    b) Confuse developers
    c) Slow down code
    Answer: a
  13. Can TypeScript infer generic types?
    a) Yes
    b) No
    Answer: a
  14. Are generics used in React?
    a) Yes
    b) No
    Answer: a
  15. Are you a generic master?
    a) Yes
    b) No
    Answer: a

πŸ”— Matching Exercises

Match the term with its definition.

TermDefinition
1. GenericA. Code that works with many types
2. Type ParameterB. Placeholder for a type
3. ConstraintC. Limits allowed types
4. InferenceD. TypeScript guesses the type
5. UtilityE. Built-in generic type

Answers: 1-A, 2-B, 3-C, 4-D, 5-E


πŸ“ Short Answer Questions

  1. What are generics and why are they useful?
  2. What is a type parameter?
  3. What is a constraint and when would you use it?
  4. What is type inference?
  5. What are three utility types you can use?

🎭 Scenario-based Exercises

  1. Scenario 1: You need to write a function that returns the first element of an array. The array can be of any type. What would you use?
  2. Scenario 2: You need to create a class that holds a single value of any type. What would you use?
  3. Scenario 3: You need to ensure that a generic type has a specific property. What would you use?

πŸ‘₯ Group Activity

β€œ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.


πŸ§‘β€πŸ’» Individual Activity

β€œ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.


πŸ—£οΈ Classroom Discussion Questions

  1. Why are generics useful?
  2. What is the difference between a generic and using any?
  3. When would you use a constraint?
  4. How does type inference make generics easier?
  5. What would you like to learn next?

πŸ› οΈ Mini Project

β€œ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.


πŸ’» Practical Assignment

β€œ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.


⚑ Challenge Exercise

β€œGeneric Challenge”

Create a complex generic function or class that uses multiple type parameters, constraints, and utility types. Share your solution with the class.


πŸ“‹ Quiz Answers

(Answers to fill-in-the-blank, true/false, and multiple choice are provided within those sections.)


🎁 Key Takeaways

  • Generics work with many types.
  • Generic functions and classes are reusable.
  • Constraints limit allowed types.
  • TypeScript can infer generic types.
  • You are a generic master.

πŸš€ Preparation for Module Eight

In Module Eight, you will learn about advanced types. To prepare:

  • Review what you learned about types.
  • Think about how types can be combined.
  • Bring your questions to the next class.

Get ready to learn about advanced types!


End of Module Seven Β· You are now a generic master!

πŸ† Get Certified

πŸ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

πŸŽ“ Sign Up to Get Certified
πŸ› οΈ Practice Tools
Hands-on simulators & labs - subscription required.
β†’
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
β†’