Welcome to today's lesson! We'll be exploring a practical application of TypeScript's type safety features by managing student enrollments for various courses. Imagine you're running an online course platform and need to handle enrollments, checks, and listings of students in different courses. With TypeScript's robust type checking and the use of Set collections, you can efficiently manage these tasks, prevent duplicate enrollments, and ensure data integrity.
By the end of this session, you'll be well-versed in using Set objects for such tasks. Let's dive in!
Here are the methods we need to implement in our enrollment system:
enroll(student, course): This method adds a student to a course. If the student is already enrolled, it does nothing.unenroll(student, course): This method removes a student from a course. It returnstrueif the student was enrolled and has now been removed. Otherwise, it returnsfalse. If, after unenrolling the student, the course becomes empty (no one is enrolled there), remove the course as well.isEnrolled(student, course): This method checks if a student is enrolled in a course. It returnstrueif the student is enrolled andfalseotherwise.listStudents(course): This method returns an array of all students enrolled in a given course. If no students are enrolled, it returns an empty array.
Let's look at how to implement each of these methods step-by-step.
We'll start by defining our class and then add each method one by one.
First, we define our EnrollmentSystem class with appropriate type annotations:
This code initializes an EnrollmentSystem class with an enrollments property. This property is a TypeScript object, where each course name maps to a Set of student names.
Next, we implement the enroll method, using type annotations for parameters:
The enroll method adds a student to a specified course. It takes two string parameters: student and course. The method checks if the course already exists in this.enrollments. If not, it initializes a new Set for the course. It then adds the student to the set, leveraging the Set to prevent duplicate enrollments.
