Skip to content

Lab: Type a Dataset

ในแบบฝึกหัดนี้ คุณจะกำหนด interfaces และ types ให้ระบบข้อมูลนักเรียน โดยใช้ความรู้ทั้งหมดจาก TS-1

คุณกำลังสร้างระบบจัดการข้อมูลนักเรียนที่ต้องมี:

  • ข้อมูลส่วนตัว (ชื่อ, อีเมล, อายุ)
  • สถานะ (active, graduated, dropped)
  • ผลการเรียน (รายวิชา, เกรด)
  • ฟังก์ชันค้นหาและกรองข้อมูล
  1. สร้าง interface สำหรับ Student

    กำหนด interface ที่มี: id, name, email, age (optional), enrolledAt (readonly)

  2. สร้าง literal type สำหรับ Status

    กำหนด status ที่เป็นไปได้: "active" | "graduated" | "dropped"

  3. สร้าง interface สำหรับ CourseResult

    กำหนด interface ที่มี: courseId, courseName, grade (A-F), score (number)

  4. สร้าง Extended interface

    สร้าง StudentRecord ที่ extend Student และเพิ่ม status, courses (array ของ CourseResult)

  5. สร้าง function signatures

    • findStudent(id: number): StudentRecord | undefined
    • filterByStatus(students: StudentRecord[], status: Status): StudentRecord[]
    • getTopStudents(students: StudentRecord[], minGpa: number): StudentRecord[]
Show Solution
// 1. Base interface
interface Student {
id: number;
name: string;
email: string;
age?: number; // optional
readonly enrolledAt: Date; // readonly
}
// 2. Status literal type
type Status = "active" | "graduated" | "dropped";
// 3. CourseResult interface
type Grade = "A" | "B+" | "B" | "C+" | "C" | "D+" | "D" | "F";
interface CourseResult {
courseId: string;
courseName: string;
grade: Grade;
score: number;
}
// 4. Extended interface
interface StudentRecord extends Student {
status: Status;
courses: CourseResult[];
}
// 5. Function implementations
function 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);