I am defining TypeScript interfaces and landed in a situation where I need to define circular interface.
Eg. ISchool have IStudent
and IStudent have ISchool
, the problem is interface ISchool {}
has IStudent
which is used before it's defined. Also, I can't define interface IStudent
before because IStudent has ISchool
. How can handle this situation?
interface ISchool {
id: string;
name: string;
students: IStudent[];
}
interface IStudent {
id: string;
name: string;
school: ISchool;
}
Better not to have circular dependencies in general. If you create a school with students the students contain a school which also contains students which also contains a school etc. That's why I reccomend you to rewrite your code so your IStudent interface references the schools with its id.
export interface ISchool {
id: string;
name: string;
students: IStudent[];
}
export interface IStudent {
id: string;
name: string;
school: string;
}
Now you can pass the id of the school to the IStudent so your IStudent interface is still linked with your ISchool interface.
Or you could disable the eslint rule by adding this to your .eslintrc.json. Because after all its jsut a lint error and javascript allows almost everything.
"no-use-before-define": "off"