Lab: Type a Dataset
Lab: Type a Dataset
Section titled “Lab: Type a Dataset”ในแบบฝึกหัดนี้ คุณจะกำหนด interfaces และ types ให้ระบบข้อมูลนักเรียน โดยใช้ความรู้ทั้งหมดจาก TS-1
คุณกำลังสร้างระบบจัดการข้อมูลนักเรียนที่ต้องมี:
- ข้อมูลส่วนตัว (ชื่อ, อีเมล, อายุ)
- สถานะ (active, graduated, dropped)
- ผลการเรียน (รายวิชา, เกรด)
- ฟังก์ชันค้นหาและกรองข้อมูล
-
สร้าง interface สำหรับ Student
กำหนด interface ที่มี: id, name, email, age (optional), enrolledAt (readonly)
-
สร้าง literal type สำหรับ Status
กำหนด status ที่เป็นไปได้:
"active"|"graduated"|"dropped" -
สร้าง interface สำหรับ CourseResult
กำหนด interface ที่มี: courseId, courseName, grade (A-F), score (number)
-
สร้าง Extended interface
สร้าง
StudentRecordที่ extendStudentและเพิ่ม status, courses (array ของ CourseResult) -
สร้าง function signatures
findStudent(id: number): StudentRecord | undefinedfilterByStatus(students: StudentRecord[], status: Status): StudentRecord[]getTopStudents(students: StudentRecord[], minGpa: number): StudentRecord[]
Show Solution
// 1. Base interfaceinterface Student { id: number; name: string; email: string; age?: number; // optional readonly enrolledAt: Date; // readonly}
// 2. Status literal typetype Status = "active" | "graduated" | "dropped";
// 3. CourseResult interfacetype Grade = "A" | "B+" | "B" | "C+" | "C" | "D+" | "D" | "F";
interface CourseResult { courseId: string; courseName: string; grade: Grade; score: number;}
// 4. Extended interfaceinterface StudentRecord extends Student { status: Status; courses: CourseResult[];}
// 5. Function implementationsfunction findStudent( students: StudentRecord[], id: number): StudentRecord | undefined { return students.find(s => s.id === id);}
function filterByStatus( students: StudentRecord[], status: Status): StudentRecord[] { return students.filter(s => s.status === status);}
function getTopStudents( students: StudentRecord[], minScore: number): StudentRecord[] { return students.filter(student => { const avg = student.courses.reduce((sum, c) => sum + c.score, 0) / student.courses.length; return avg >= minScore; });}
// ตัวอย่างการใช้งานconst sampleData: StudentRecord[] = [ { id: 1, name: "สมชาย", email: "somchai@uni.ac.th", enrolledAt: new Date("2024-06-01"), status: "active", courses: [ { courseId: "CS101", courseName: "Intro to CS", grade: "A", score: 92 }, { courseId: "CS201", courseName: "Data Structures", grade: "B+", score: 85 } ] }];
const activeStudents = filterByStatus(sampleData, "active");const topStudents = getTopStudents(sampleData, 80);