I am teaching a class on TypeScript basics and I realized something that is really confusing to students and also to me. If I define my TypeScript data model like this
interface Person {
name: string;
age: number;
}
interface Teacher extends Person {
subject: string;
}
interface Student extends Person {
grade: number;
}
I cannot actually do the following which my students expect to by possible from experience with other languages such as Java, C# etc.
const people: Person[] = [
{ name: "Alice", age: 30, grade: 100 },
{ name: "Bob", age: 25, subject: "Math"},
];
I would argue, ther extends does not create a proper subtype/supertype relationship. It only copies properties from one type to onether. To make this work you need to do this:
interface BasePerson {
name: string;
age: number;
}
interface Teacher extends Person {
subject: string;
}
interface Student extends Person {
grade: number;
}
type Person = Teacher | Student;
But I am unable to explain to my students why extends works this way. And also, I am not even sure that my solution is the prefered one. Am I getting it completely wrong and there is a better way to structure data models?