0

Is it possible to extend such as way?

export interface IClass<T extends ISubject> {
  subject : T;
  course : ICourse<T>;
}

export interface ICourse<T> extends T { }

export interface ISubject { }

Where a ClassRoom can implement IClass that teaches Math, English. However, the course should be relevant to the Subject. Such that, Math will have the following courses: MAT101, MAT205 etc. and English has ENG232, ENG302 etc..

This way they are tightly coupled to their respective interface. Ie. you should not be able to pass in subject as Math and course as ENG232

Currently it complains at extends T for the ICourse interface as: An interface can only extend an object type or intersection of object types with statically known members.

1 Answer 1

1

You cannot extends a generic type so this statement is incorrect

export interface ICourse<T> extends T { }

I would split the subject code (MAT, ENG) and the number (205, 232) in the Course.

export enum Subject {
  Math = "MAT",
  English = "ENG"
}

export interface Course {
  subjectCode: SubjectCode,
  courseId: number,
}

Then you can have course like:

const math101: Course = { subjectCode: Subject.Math, courseId: 205 };
const english232: Course = { subjectCode: Subject.English, courseId: 232 };

It also note that you should not think of Generic Type as how you combine interface together. It should be use in case when you don't have the type of your interface/class and want the user of that generic interface/type to declare it.

For example, you don't know the courseId is string or number. You can make a Course interface like this.

export interface Course<T> {
  subjectCode: SubjectCode,
  courseId: T,
}

And then the usage is:

const math101: Course<string> = { subjectCode: Subject.Math, courseId: "205" };
const english232: Course<number> = { subjectCode: Subject.English, courseId: 232 };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the respond. Just a side note i just used Course and Subject as an example, i'll need to have them as interface only because they'll be implemented by a lot more complex class. Also you are assuming that MAT205 exist and ENG205 doesn't, right? How would you solve for this case? Also please no enums or Types only because the children of these implementation are very complex and i just want to say Implement this interface and the implementor of the Course should also use Subject's same class name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.